在WordPress中的循环中循环


Loop within a loop in WordPress

我在WordPress中的一些PHP代码中遇到了问题,我认为解决方案与循环有关。我看了一眼 http://codex.wordpress.org/The_Loop 和 http://codex.wordpress.org/The_Loop_in_Action 但它超出了我的头脑,我已经浪费了整个星期六

所以问题是我在网站的主页上有一个小部件。它显示接下来发生的 5 个事件的标题以及指向它们的链接。我想做的是显示事件(它们就像博客文章(上次修改的日期。

问题是我的代码不断返回错误的日期。我今天修改了我的帖子,12月13日,它一直在输出12月11日。我不知道它从哪里得到那个日期。我尝试同时使用 the_modified_date(( 和 get_the_modified_date(( 的结果相同。我猜该函数不知道从哪个帖子中提取日期,它与循环有关。

所以我一直在弄乱小部件的代码。这是我所拥有的简化版本:

foreach ($events as $event) {
  if ( $event['event_date'] >= $site_date ) {
    $lastMod = get_the_modified_date($phpformatstring);
    echo $lastMod;
    echo '<br><a href="' . get_permalink($event['ID']) . '"  >' . get_the_title($event['ID']) . '</a>';
    if ( !empty( $widget_display_count ) ) {
      $counter++;
      if ( $counter == $widget_display_count )
        break;
    }
  }
}

真的希望有人能帮助我。如果您想使用我正在使用的小部件尝试一下,它被称为事件列表小部件

get_the_modified_date()需要全局$post。该插件正在迭代 wpdb 查询的结果,因此从技术上讲没有 WP 循环。

get_the_modified_date()调用之前global $post; $post = get_post( $event['ID'] ); setup_postdata( $post );之类的东西应该可以工作。不要忘记之后使用wp_reset_postdata();重置帖子数据

get_the_modified_date()作用

于循环中的当前帖子。

该函数使用 get_post_modified_time() 来获取将接受帖子 ID 的日期。

取代:

$lastMod = get_the_modified_date($phpformatstring);

跟:

$lastMod = get_post_modified_time( $phpformatstring, null, $event['ID'], true );