我用WP_query循环检索了首页的最新帖子,因为我发现这是最好的解决方案。但我想显示的帖子是在首页被点击的。
单站查询最好的方法是什么?
我在single.php中再次使用了wp_query (还有更好的主意吗?)
$args = array('name' => $the_slug,
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 1);
$the_query = new WP_Query( $args );
<?php while ( $the_query->have_posts() ) :?>
<?php $the_query->the_post(); ?>
<p><?php $content = get_the_content('Read more');
print $content; ?></p>
<?php endwhile; ?><!-- end of the loop -->
<!-- put pagination functions here -->
<?php wp_reset_postdata(); ?>
<?php else: ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>问题是它总是检索最新的帖子,即使我点击了任何帖子的id。我该如何解决这个问题呢?
发布于 2014-09-01 22:57:34
不要在主循环的位置运行自定义查询。你可以简单地做下面的事情,它是更快,更可靠和正确的方法
<?php
// Start the Loop.
while ( have_posts() ) : the_post();
// YOUR LOOP ELEMENTS
endwhile;
?>编辑
上面的代码被称为循环,确切地说是默认的循环。这不是查询。这个循环的作用是,它只返回由主查询检索到的信息。主查询在加载的每个页面的上运行。主查询是特定于每个页面的
有关更多信息,请阅读有关此问题的my post on WPSE
发布于 2014-09-01 22:32:46
我找到了解决方案。
创建此变量$id= get_the_ID();
并添加'p'=>$id to $args.
发布于 2020-05-01 05:17:18
$my_query = new WP_Query( array(
'post_type' => 'your_post_type_here',
'p' => '$id'));// need to set the simple quote '$id'
if( $my_query->have_posts() ){
// start the loop
}else{
// no result message
}不要忘记在'$id‘中添加简单的引号,因为我尝试了没有,但它在我的情况下不起作用。希望它能在未来帮助某些人!
https://stackoverflow.com/questions/25607884
复制相似问题