从类别中获取所有图像网址 - Wordpress

时间:2013-04-17 12:51:12

标签: wordpress

我想获取我的类别3的所有图片附件ID。 有人知道怎么做吗?

这是我的代码:

    $query_images_args = array(
        'post_type' => 'attachment',
        'post_mime_type' =>'image',
        'post_status' => 'inherit',
        'posts_per_page' => -1,     
//      'cat'=> 3, NOT WORKING 
        'orderby' => 'rand', // Order randomly 
    );

    $query_images = new WP_Query( $query_images_args );
    $images_desktop = array();
    $images_tablets = array();
    $images_smartphones = array();


    // WE ARE GETTING ALL IMAGES URLS ACCORDING TO THE DEVICE
    foreach ( $query_images->posts as $image) {

    $attachment_width = wp_get_attachment_image_src($image->ID,'small');
    $attachment_width = $attachment_width[1];
        if($attachment_width<=500)
        {
            $images_smartphones[] = wp_get_attachment_url( $image->ID);
        }
        elseif ($attachment_width<=1000)
        {
            $images_tablets[] = wp_get_attachment_url( $image->ID);
        }
        elseif ($attachment_width>=1000){
            $images_desktop[]= wp_get_attachment_url( $image->ID);
        }
    }
    ?>

我的想法:

如果他们有任何图片附件,请获取类别3的所有帖子ID。 通过这个帖子ID列表,我可以获得每个附件ID的列表。 这是对的吗?

由于

1 个答案:

答案 0 :(得分:1)

这是我的工作代码

<?php wp_reset_query();

// Init 
    $images_desktop = array();
    $images_tablets = array();
    $images_smartphones = array();

    $args = array( 
        'orderby' => 'rand',
        'post_type' => 'post', 
        'cat' => 3, 
        'posts_per_page' => -1,
     );

    $wp_query = new WP_Query($args);                
// $wp_query->posts returns all posts even childrens

    foreach ( $wp_query->posts as $single_post) {
        $single_post_ID = $single_post->ID;
//      echo ($single_post_ID."<br/>");
        $args = array(
            'orderby' => 'rand', // Order randomly 
            'post_type'      => 'attachment',
            'post_parent'    => $single_post_ID,
            'post_mime_type' => 'image',
            'post_status'    => null,
            'numberposts'    => -1,
        );

        $attachments = get_posts($args);
        if ($attachments) {
            foreach ($attachments as $attachment) {
                $attachment_ID = $attachment->ID;

                $attachment_width = wp_get_attachment_metadata($attachment_ID);
                $attachment_width = $attachment_width["width"];
                if($attachment_width<=500)
                {
                    $images_smartphones[] = wp_get_attachment_url( $attachment_ID);
                }
                elseif ($attachment_width<=1000)
                {
                    $images_tablets[] = wp_get_attachment_url($attachment_ID);
                }
                elseif ($attachment_width>=1000){
                    $images_desktop[]= wp_get_attachment_url($attachment_ID);
                }

            }
        } 
    }

    ?>