WP查询检索附加图像的src

时间:2017-05-02 13:10:35

标签: json wordpress

我在JSON中编码来自WP Query的一堆数据:

$args = array(
    'posts_per_page' => 20,
    'post_type' => 'post',
    'category' => 6,
    'meta_key' => 'custom_total_hits',
    'tag' => 'indie-pop',
    'orderby' => 'meta_value_num',
    'order' => 'DESC',
    'date_query' => array(
        'after' => date('Y-m-d', strtotime('-40 days')) 
    )
); 

$query = new WP_Query( $args ); 
$posts = $query->get_posts();   

foreach( $posts as $post ) {    
    $output[] = array( 
    'id' => $post->ID, 
    'title' => $post->post_title, 
    'count' => $post->custom_total_hits, 
    'soundcloud_url' => $post->soundcloud_song, 
    'soundcloud_id' => $post->soundcloud_ids, 
    'link' => get_permalink($post), 

);
 }     

echo json_encode($output);

我想在我的JSON中显示一个与附加图像的中等大小的src相对应的键。如果我使用'images' => get_attached_media('image', $post->ID)它会检索我无法访问的多个数据的数组,因为在处理我的JSON数据时我不知道附加图像的ID。如何检索第一级键 - 值是附加图像的src值?

2 个答案:

答案 0 :(得分:1)

get_post_thumbnail_id:获取帖子缩略图ID

wp_get_attachment_url:按附件ID

获取附件网址
'images' => parse_url( wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) ) );

请您尝试上面的代码吗?

答案 1 :(得分:1)

试试这个解决方案:

$images = array();
$post_thumbnail_id = get_post_thumbnail_id( $post->ID );

foreach (get_intermediate_image_sizes() as $size) {
    $images[$size] = wp_get_attachment_image_src($post_thumbnail_id, $size);
}


//end

'images' => $images // type_of_size => image_url