[英]query single post with wp_query
I retrieved the latest posts in front page with WP_query loop, coz i figured out that's the best solution.我用 WP_query 循环检索了首页上的最新帖子,因为我发现这是最好的解决方案。 but i want to display the post was clicked in front page.
但我想显示帖子被点击在首页。
what's the best method for single post query?单个帖子查询的最佳方法是什么?
I used wp_query again in single.php(is there any better idea?)我在 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; ?>
the problem is it always retrieved the latest post, even i click on any post id.问题是它总是检索最新的帖子,即使我点击任何帖子 ID。 how can i fix that problem?
我该如何解决这个问题?
I found the solution.我找到了解决方案。
create this variable $id= get_the_ID();
创建这个变量
$id= get_the_ID();
and add 'p'=>$id to $args.
并将
'p'=>$id to $args.
Don't run a custom query in place of the main loop.不要运行自定义查询来代替主循环。 You can simply just do the following, it is faster, more reliable and the correct way
您可以简单地执行以下操作,它更快,更可靠和正确的方法
<?php
// Start the Loop.
while ( have_posts() ) : the_post();
// YOUR LOOP ELEMENTS
endwhile;
?>
EDIT编辑
The above code is called the loop, the default loop to be exact.上面的代码称为循环,确切地说是默认循环。 This is not a query.
这不是查询。 What this loop does, it returns only the information retrieved by the main query.
这个循环的作用是只返回主查询检索到的信息。 The main query runs on every page that loads .
主查询在加载的每个页面上运行。 The main query is specific for every page
主要查询特定于每个页面
For more info, read my post on WPSE regarding this matter有关更多信息,请阅读我在 WPSE 上关于此事的帖子
$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
}
dont forget to add simple quote to '$id' because i tried without and it was not working in my case.不要忘记在 '$id' 中添加简单的引号,因为我没有尝试过,但在我的情况下它不起作用。 hope it helps someone in the future !
希望它可以帮助未来的人!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.