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 badges1 Answer
Reset to default 0You 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
版权声明:本文标题:theme development - Loop through all posts, show attachment if there 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745584715a2664830.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论