获取Wordpress图像URL不起作用

时间:2014-02-08 17:32:30

标签: php arrays wordpress image woocommerce

我使用以下内容获取Wordpress Woocommerce产品的数据。我在json中输出产品数据。

 <?php
 $args = array( 'post_type' => 'product', 'posts_per_page' => 200, 'product_cat' => 'clothes');
       $loop = new WP_Query( $args );


    $send_array = array();
       while ( $loop->have_posts() ) : $loop->the_post(); 
        global $product; 

    $send_array[] = array(

        'id' => get_the_ID(),
        'title' => get_the_title(),
        'content' => get_the_content(),
        'regular_price' => get_post_meta( get_the_ID(), '_regular_price', true),
        'image' =>wp_get_attachment_image_src(),
        'sale_price'=> get_post_meta( get_the_ID(), '_sale_price', true)
    );

     endwhile; 

     wp_reset_query(); 
        ob_clean();
        echo json_encode($send_array);
        exit();

    ?>

此代码工作正常并正确输出数据。但是image似乎不起作用。

我想获取每个产品的图片网址。在上面的代码中,我尝试了wp_get_attachment_image_src(),但没有运气。

如何使用上面的代码获取每个产品的图片网址,并将其作为数组中image键的值。

1 个答案:

答案 0 :(得分:2)

问题在于你没有主动调用wp_get_attachment_image_src()函数。 它需要所需附件的ID,您可以使用get_post_thumbnail_id()函数获取。

但是wp_get_attachment_image_src()会返回一个数组,其中包含附件文件的图片属性"url""width""height"

我建议使用wp_get_attachment url()函数,它只返回一个URL。

Finnaly,这段代码应该适合你:

 $send_array[] = array(

    'id' => get_the_ID(),
    'title' => get_the_title(),
    'content' => get_the_content(),
    'regular_price' => get_post_meta( get_the_ID(), '_regular_price', true),
    'image' => wp_get_attachment_url( get_post_thumbnail_id( get_the_ID() ) ),
    'sale_price'=> get_post_meta( get_the_ID(), '_sale_price', true)
);

有关wordpress codex上此功能的更多信息:

http://codex.wordpress.org/Function_Reference/get_post_thumbnail_id

http://codex.wordpress.org/Function_Reference/wp_get_attachment_image_src

http://codex.wordpress.org/Function_Reference/wp_get_attachment_url