admin管理员组

文章数量:1431398

I've created two simple foreach loops: one for all posts, one for all attachments. I want it show every post title, and if there is an attachment, show that attachment.

I have, thus far:

$get_posts_array = array( 'posts_per_page' => 3, 'post_type' => 'post' );
$get_posts = get_posts( $get_posts_array );

foreach ($get_posts as $post)
{
    the_title();

    $get_images_array = array( 'posts_per_page' => 1, 'post_type' => 'attachment' );
    $get_images = get_posts($get_images_array);

    if ($get_images)
    {
        foreach ( $get_images as $post )
        {
        ?>
            <li> <?php the_attachment_link( $post->ID ) ;?> </li>
        <?php
        } 
    }
}
?>

However, it is not working as expected.

It retrieves every post title, but uses the same first attachment for all posts.

Any help would be great (I'm inexperienced with PHP, so this could be completely buggy).

I've created two simple foreach loops: one for all posts, one for all attachments. I want it show every post title, and if there is an attachment, show that attachment.

I have, thus far:

$get_posts_array = array( 'posts_per_page' => 3, 'post_type' => 'post' );
$get_posts = get_posts( $get_posts_array );

foreach ($get_posts as $post)
{
    the_title();

    $get_images_array = array( 'posts_per_page' => 1, 'post_type' => 'attachment' );
    $get_images = get_posts($get_images_array);

    if ($get_images)
    {
        foreach ( $get_images as $post )
        {
        ?>
            <li> <?php the_attachment_link( $post->ID ) ;?> </li>
        <?php
        } 
    }
}
?>

However, it is not working as expected.

It retrieves every post title, but uses the same first attachment for all posts.

Any help would be great (I'm inexperienced with PHP, so this could be completely buggy).

Share Improve this question asked Feb 27, 2014 at 17:36 tmyietmyie 8732 gold badges13 silver badges21 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

You can't use the_title() as you haven't set up the post data.

Instead for the title you need to use:

$post->post_title;

To get the attachments you can then use get_children() something like this:

$args = array(
    'numberposts' => 1,
    'post_parent' => $post->ID,
    'post_type' => 'attachment'
);

$attachments = get_children( $args );

foreach($attachments as $attachment) {
  // Do your stuff
}

The thing is there might be multiple attachments on a post, so it might not be predictable. Also what kind of attachment do you want to get? You can use:

'post_mime_type' => 'image'

for example, as part of the argument - if you only want images.

What might be better, if you have the option, is to use the post thumbnail or a meta key/value (custom field) instead so the user can specifically add an attachment.

本文标签: theme developmentLoop through all postsshow attachment if there