0

我想获取我的类别 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 的列表。这个对吗?

谢谢

4

1 回答 1

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);
                }

            }
        } 
    }

    ?>
于 2013-04-18T12:17:37.847 回答