Wordpress循环显示限制帖子

时间:2010-10-06 18:49:22

标签: wordpress

这是基本循环

<?php while (have_posts()) : the_post(); ?>

我想在搜索结果页面上显示20个帖子。我知道我们可以更改管理面板选项的值,但它会更改所有内容,即索引页面和存档页面等。我需要以不同的方式更改它们。

5 个答案:

答案 0 :(得分:11)

很好的参考:http://codex.wordpress.org/The_Loop

在调用while语句之前,您需要查询帖子。所以:

  <?php query_posts('posts_per_page=20'); ?>

  <?php while (have_posts()) : the_post(); ?>
    <!-- Do stuff... -->
  <?php endwhile;?>

编辑:对于分页感到抱歉,试试这个:

    <?php 
        global $query_string;
        query_posts ('posts_per_page=20');
        if (have_posts()) : while (have_posts()) : the_post();
    ?>
    <!-- Do stuff -->
    <?php endwhile; ?>

    <!-- pagination links go here -->

    <? endif; ?>

答案 1 :(得分:4)

我找到了这个解决方案,它对我有用。

 global $wp_query;
 $args = array_merge( $wp_query->query_vars, ['posts_per_page' => 20 ] );
 query_posts( $args );

 if(have_posts()){
   while(have_posts()) {
     the_post();
     //Your code here ...
   }
 }

答案 2 :(得分:1)

您可以通过$ wp_query对象限制每个循环的帖子数。 它需要多个参数,例如:

<?php 
$args = array('posts_per_page' => 2, 'post_type' => 'type of post goes here');
$query = new WP_Query( $args );
while( $query->have_posts()) : $query->the_post();
<!-- DO stuff here-->
?>

有关wp_query对象 here->

的更多信息

答案 3 :(得分:0)

添加'paged'=&gt; $ paged Pagination会起作用!

<?php 
$args = array('posts_per_page' => 2, 'paged' => $paged);
$query = new WP_Query( $args );
while( $query->have_posts()) : $query->the_post();
<!-- DO stuff here-->
?>

答案 4 :(得分:0)

模板内新查询的答案无法与自定义帖子类型一起正常使用。

documentation提供挂钩任何查询,检查是主查询,并在执行前修改它。这可以在模板函数中完成:

function my_post_queries( $query ) {
  // do not alter the query on wp-admin pages and only alter it if it's the main query
  if (!is_admin() && $query->is_main_query()) {
    // alter the query for the home and category pages 
    if(is_home()){
      $query->set('posts_per_page', 3);
    }

    if(is_category()){
      $query->set('posts_per_page', 3);
    }
  }
}
add_action( 'pre_get_posts', 'my_post_queries' );
相关问题