【问题标题】:query single post with wp_query使用 wp_query 查询单个帖子
【发布时间】:2014-09-01 14:21:10
【问题描述】:

我使用 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 html wordpress codex


    【解决方案1】:

    我找到了解决方案。

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

    并添加'p'=&gt;$id to $args.

    【讨论】:

      【解决方案2】:

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

      <?php
                  // Start the Loop.
          while ( have_posts() ) : the_post(); 
      
              // YOUR LOOP ELEMENTS
      
          endwhile;
      ?>
      

      编辑

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

      欲了解更多信息,请阅读my post on WPSE了解此事

      【讨论】:

      • 谢谢,请问是什么查询?它使用 wp_query 还是 query_post?我只想在主页中显示最近的 5 个帖子并为此使用分页。我该如何更改该属性?
      • 请看我的更新。还可以查看捆绑的主题并了解它们的结构
      • 很高兴它有帮助 :-) 享受
      【解决方案3】:
      $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' 中添加简单的引号,因为我尝试不使用它,但它在我的情况下不起作用。希望它对未来的人有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-09-08
        • 1970-01-01
        • 1970-01-01
        • 2021-07-01
        • 1970-01-01
        • 2013-02-05
        • 1970-01-01
        相关资源
        最近更新 更多