【问题标题】:WP Query foreach loop - repeats the same postWP Query foreach 循环 - 重复相同的帖子
【发布时间】:2014-04-03 00:28:29
【问题描述】:

我已经为此花费了几个小时 - 希望懂一点 PHP 的人可以轻松解决它。

我有一个需要连接在一起的 Wordpress 查询循环。它有点工作,但我请求了 6 个帖子,所有 6 个都是一样的!

这是返回重复帖子的代码 sn-p:

////* New tab *//////

$args = array( 'numberposts' => 6, 'orderby' => 'post_date' );
$postslist = get_posts( $args );
$content .= '<div class="tab" id="new"><ul>';

foreach ($postslist as $post) :  setup_postdata($post);

  $content .= '<li><a href="' .  get_permalink() . '"</a>' . get_the_title() . '</a></li>';

endforeach; 

$content .= '</ul></div>';
return $content; // prints all the contents stringed together

此代码生成此列表:

任何帮助表示赞赏...在所有!谢谢。

【问题讨论】:

  • 那么你的问题是什么?为什么它给你6件事?首先,实际上是否有 6 件东西会被退回,或者你是说你希望重复的东西只显示一次?我的猜测是,既然你向get_posts() 询问了 6 件事,它就给了你 6 件事。看来您需要检查是否有重复项。
  • 您是否有重复的帖子,或者您有六个或更多不同的帖子?
  • 是的,循环正在生成最新的帖子,但是 6 次。
  • 是的,我正在尝试获取最近的帖子,而不是多次发布相同的帖子。

标签: php wordpress loops


【解决方案1】:

看起来您的代码示例是从函数内部获取的。

a) 请试试这个:

// ... cut ...
global $post;  
$args = array( 'posts_per_page' => 6, 'orderby' => 'post_date' );
$postslist = get_posts( $args );
$content .= '<div class="tab" id="new"><ul>';
foreach ( $postslist as $post ) :  setup_postdata( $post );
    $content .= sprintf( '<li><a href="%s">%s</a></li>',  
                          get_permalink(),
                          get_the_title() );
endforeach; 
$content .= '</ul></div>';
wp_reset_postdata();
return $content; // prints all the contents stringed together

我在其中添加了global $post 声明,因此setup_postdata( $post ) 可以修改全局$post 对象。

b) 或者试试这个:

// ... cut ...
$args = array( 'posts_per_page' => 6, 'orderby' => 'post_date' );
$postslist = get_posts( $args );
$content .= '<div class="tab" id="new"><ul>';
foreach ( $postslist as $post ) :
    $content .= sprintf( '<li><a href="%s">%s</a></li>',  
                          get_permalink( $post->ID ),
                          get_the_title( $post->ID ) );
endforeach; 
$content .= '</ul></div>';
return $content; // prints all the contents stringed together

我使用帖子 ID 作为 get_permalink() 和 get_the_title() 的输入参数。

c)您还可以使用原始帖子标题:$post-&gt;post_title,或者如果您想通过 the_title 过滤器使用:

echo apply_filters( 'the_title', $post->post_title );

总结一下:

注意get_the_title()是基于get_post()的,如果你不使用输入参数,那么它将尝试使用全局$post对象:

if ( empty( $post ) && isset( $GLOBALS['post'] ) )
    $post = $GLOBALS['post'];

因此,如果您不在辅助循环中修改全局对象,您总是会获得相同的全局帖子对象标题(通常来自主查询)。

希望这会有所帮助。

【讨论】:

  • Birgire。是的,第一个解决方案奏效了。这一切都在循环中,你的吐出最新的。好东西。非常感谢!马丁
猜你喜欢
  • 2017-05-26
  • 1970-01-01
  • 2019-05-17
  • 2011-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多