I am struggling with the following while working on a WordPress theme:
as the title suggests, the array returned by get_posts() is frequently empty despite posts definitely holding images.
I am using the following to retrieve the attachments-array:
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_parent' => $post_id
) );
Now, the $post_id works perfectly fine…if I echo it right before the above snippet it shows without fail. I can’t make out where the error is.
For the sake of completeness, heres the whole loop, which works perfectly fine in every regard except the attachment retrieval:
<?php if (have_posts()) : ?>
<?php while (have_posts()) : ?>
<?php the_post(); ?>
<div class="post" id="post-<?php the_ID(); ?>">
<div class="post-border">
<div class="post-date"><?php edit_post_link('Edit Post', '', ''); ?></div>
<?php if($pagename == 'news'): ?>
<div class="post-date">Posted: <?php the_time('F j, Y') ?></div>
<?php endif; ?>
<h5 class="posttitle"><?php the_title(); ?></h5>
<div class="post-entry">
<?php the_content(); ?>
<?php
$post_id = $post -> ID;
echo $post_id;
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => 20,
'post_parent' => $post_id
) );
print_r($attachments);
?>
<?php echo "<div class='clearboth'></div>"; ?>
</div> <!-- end of .entry -->
</div> <!-- end of .post-border -->
</div> <!-- end of .post -->
<?php endwhile; ?>
<?php endif; ?>
If anyone has any suggestions I’d be very grateful!
Best,
J
Attachments inherit
post_status
from the parent post, so add the following to the args:I found out in WordPress 4.1 that when you insert an image from the images previously uploaded to the media library, it is not treated as attachment. So, in order to create image attachments for the post, the images should be first uploaded as files to media library (“add media-“upload files) and only then selected and inserted into the post.
Make sure the images are attached to that post, not just inserted into the post body.
Another gotcha to watch for: if you’re using a command-line script that uses WP functions, ensure that there is a valid logged-in user (e.g. admin). Otherwise
get_posts()
will not return any posts that aren’t ordinarily public (such as attachments to drafts or scheduled posts). That is easily achieved with something likewp_set_current_user(1,'admin');
The problem is attachments have post_status == ‘inherit’ not ‘publish’ so I would try adding
to your argument list.
Note that this may get more results then intended as post_type == ‘post’ with post_status == ‘inherit’ will also be returned. You should probably do two separate queries. This is just an explanation as to why your combined query does not work as expected.
The reason
works is the WordPress has the following code in get_posts()