0

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

4

3 回答 3

5

我找到了解决方案。

创建这个变量$id= get_the_ID();

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

于 2014-09-01T14:32:45.560 回答
2

不要运行自定义查询来代替主循环。您可以简单地执行以下操作,它更快,更可靠且正确的方法

<?php
            // Start the Loop.
    while ( have_posts() ) : the_post(); 

        // YOUR LOOP ELEMENTS

    endwhile;
?>

编辑

上面的代码称为循环,确切地说是默认循环。这不是一个查询。这个循环做什么,它只返回主查询检索到的信息。主查询在加载的每个页面上运行。主要查询特定于每个页面

有关更多信息,请阅读我在 WPSE 上关于此问题的帖子

于 2014-09-01T14:57:34.120 回答
0
$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' 中添加简单的引号,因为我试过没有,但在我的情况下它不起作用。希望它对未来的人有所帮助!

于 2020-04-30T21:17:18.367 回答