我使用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。我该如何解决这个问题?
不要在主循环中运行自定义查询。您只需执行以下操作即可,它更快,更可靠且方法正确]
<?php
// Start the Loop.
while ( have_posts() ) : the_post();
// YOUR LOOP ELEMENTS
endwhile;
?>
编辑
上面的代码称为循环,确切地说是默认循环。这不是查询。此循环的作用是,它仅返回主查询检索到的信息。主查询在加载的每个页面上运行。主要查询针对每个页面]
有关更多信息,请阅读有关此问题的my post on WPSE
我找到了解决方案。
创建此变量$id= get_the_ID();
并添加'p'=>$id to $args.
$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'中添加简单的引号,因为我尝试过不这样做,并且在我的情况下不起作用。希望它对以后的人有所帮助!