使用wpquery查询单个帖子


query single post with wp_query

我用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。我该如何解决这个问题?

我找到了解决方案。

创建此变量$id= get_the_ID();

并添加'p'=>$id to $args.

不要在主循环中运行自定义查询。你可以简单地做以下几点,它是更快,更可靠和正确的方式
<?php
            // Start the Loop.
    while ( have_posts() ) : the_post(); 
        // YOUR LOOP ELEMENTS
    endwhile;
?>

编辑

上面的代码被称为循环,确切地说是默认的循环。这不是一个查询。这个循环只返回主查询检索到的信息。主查询在加载的每个页面上运行。主查询针对每一页

有关更多信息,请阅读我在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
}

别忘了在"$id"后面加上一个简单的引号,因为我试过不加引号,但在我的情况下不起作用。希望它将来能帮助到别人!