简体   繁体   中英

Wordpress wp_get_attachment_image doesn't show images for every post

wp_get_attachment_image() gets images only for 2 out of 5 posts.

I am new to WordPress, I am making theme where main page only shows images (attachments) from posts. Posts are all in the same manner - title, paragraph, and gallery. Each of them have category assigned to it. Tried to fix the problem in many ways but none seem to be working. I've dumped every post and it seems that

$postyMarkiQq = new WP_Query( array( 'category_name' => 'marki' ) );
$posty = $postyMarkiQq->posts;

gets information properly. I've tried using get_attached_media('', $post->ID) but it returns same results. I've tried putting the main part of the code to function.

<?php
    $postyBrandQ = new WP_Query( array( 'category_name' => 'brand' ) );
    $posty = $postyBrandQ->posts;

    foreach($posty as $post) {
        echo $post->ID;
    ?>

    <div class="category">
        <?php
            echo get_the_title( $post->ID );
            $args = array(
                'post_parent' => $post->ID,
                'post_type' => 'attachment',
                'post_mime_type' => 'image',
                'posts_per_page' => -1,
                'orderby' => 'menu_order',
                'order' => 'ASC',
            );
            $attachments = get_children( $args );
            foreach ( $attachments as $attachment ) {
                echo wp_get_attachment_image($attachment->ID);
            }
            wp_reset_postdata();
        ?>
    </div>

    <?php
    }
    ?>

I don't have any idea why wouldn't this work. Would really appreciate help. Thanks!

You probably shouldn't be querying by post parent. Attachments are only given post parents based on the page you are currently viewing when you upload the item to the media library. If you click media, and upload images, the images won't have a post parent, even if you go to a post (or page) later on, and set that image as the featured image.

So, I don't know the exact context of your question, but perhaps get_post_thumbnail_id( $post->ID ) will be the answer you are looking for. This will return the attachment ID of the featured image, then you can use wp_get_attachment_image_src() (pass in the attachment ID probably), which will return you an array. Print the array, in there somewhere you will find the URL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM