【问题标题】:Foreach is not iterating properly /with WordPressForeach 没有正确迭代/使用 WordPress
【发布时间】:2017-03-12 06:41:51
【问题描述】:

我正在尝试遍历最近的三个帖子并显示它们的缩略图、标题和永久链接。

第一个的外观略有不同,因此还有一个 if 语句以不同的设置显示第一个,然后遍历其余部分。相反,它在 if 和 else 的样式中显示了第一篇文章 3 次。

我不知道我做错了什么,感谢您的帮助!

<?php
      $recent =  wp_get_recent_posts( array('numberposts' => 3) );
        $i = 0;
        global $recent_post;
        foreach( $recent as $recent_post ) {
          if ($i == 0 ): ?>
              <div class="header_recent main">
                <a href="<?php the_permalink($recent_post); ?>">
                  <img src="<?php echo get_the_post_thumbnail($recent_post->ID); ?>"/>
                  <div class="overlay">
                    <h1><?php the_title_attribute($recent_post); ?></h1>
                  </div>
                </a>
              </div>
      <?php else: ?>
          <div class="header_recent side">
            <a href="<?php the_permalink($recent_post); ?>" title="<?php the_title_attribute($recent_post); ?>">
            <img src="<?php echo get_the_post_thumbnail($recent_post->ID); ?>"/>
                <div class="overlay">
                  <h1><?php the_title_attribute($recent_post); ?></h1>
                </div>
          </div>
    <?php endif; $i++; }
  wp_reset_postdata();
?>

另外,我非常感谢有关 get_the_post_thumbnail 函数的警告的帮助:

注意:试图在线获取非对象的属性 29

【问题讨论】:

    标签: php html wordpress if-statement foreach


    【解决方案1】:

    函数wp_get_recent_posts()默认返回ARRAY,你可以在documentation中看到。在您的情况下,您需要将第二个参数$output 作为OBJECT 传递:

    $recent =  wp_get_recent_posts( array( 'numberposts' => 3 ), OBJECT );
    

    您也不应该将$recent_post 作为the_title_attribute() 函数的参数传递。所以而不是:

    <h1><?php the_title_attribute($recent_post); ?></h1>
    

    你可以写:

    <h1><?php echo $recent_post->post_title; ?></h1>
    

    而且您不需要将$recent_post 声明为global

    【讨论】:

      猜你喜欢
      • 2021-06-07
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多