WP查询检索附加图像的源

时间:2017-05-02 作者:LucaP

我正在用JSON编码来自WP查询的一组数据:

$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。如何检索第一级key : value 其中,值是附加图像的src?

1 个回复
最合适的回答,由SO网友:Aishan 整理而成

您可以使用wp_get_attachment_image_src 并获取所需大小的图像,然后传递到阵列上:

foreach( $posts as $post ) {
    $imgsrc = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), "medium" );
    $imgsrc = $imgsrc[0];

    $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), 
    \'image_src\' => $imgsrc
    );
 }     

echo json_encode($output);