【问题标题】:Loop through all posts, show attachment if there (WordPress)循环浏览所有帖子,如果有则显示附件(WordPress)
【发布时间】:2014-02-27 17:23:54
【问题描述】:

我创建了两个简单的foreach 循环:一个用于所有帖子,一个用于所有附件。我希望它显示每个帖子标题,如果有附件,请显示该附件。

到目前为止,我有:

$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
        } 
    }
}
?>

但是,它没有按预期工作。

它检索每个帖子标题,但对所有帖子使用相同的第一个附件。

任何帮助都会很棒(我对 PHP 没有经验,所以这可能完全是错误的)。

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    根据您提供的代码,您所说的是遍历所有帖子,对于每个帖子,循环遍历所有附件并返回第一个附件,然后转到下一个帖子。您需要一个将附件与帖子联系起来的标识符。例子: 您有一组 ID 为 1、3、5、7 的帖子。当您遍历帖子数组时,您想要获取与您当前正在循环的特定帖子 ID 相关联的附件。

    希望对您有所帮助。我不精通 WordPress 语法,但我认为它会类似于...

    $get_images_array = array( 'posts_per_page' =&gt; 1, 'post_type' =&gt; 'attachment', 'post_id' =&gt; $post-&gt;ID );

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 1970-01-01
      相关资源
      最近更新 更多