ray
ray

Reputation: 111

Wordpress loop show limit posts

This is the basic loop

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

I want to show 20 posts on the search results page. I know we can change the value on admin panel options but it will change all i.e. index page and archive page etc. I need to have them differently.

Upvotes: 11

Views: 58162

Answers (6)

Stavros
Stavros

Reputation: 831

Just before you call the if statement, you need to query the posts.

This one works with archive, custom post types etc.

global $query_string;
query_posts( $query_string . '&posts_per_page=12' );

if ( have_posts() ) : 

Upvotes: 0

nayeri
nayeri

Reputation: 175

I find this solution and it works for me.

 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 ...
   }
 }

Upvotes: 9

Answers with new query inside template will not work correctly with custom post types.

But documentation offers to hook on any query, check is it main query, and modify it before execution. That can be done inside template functions:

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' );

Upvotes: 1

Daman
Daman

Reputation: 521

Add 'paged' => $paged Pagination would work!

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

Upvotes: 1

n1cko_r
n1cko_r

Reputation: 392

You can limit the number of posts per loop through a $wp_query object. it takes multiple parameters for example:

<?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-->
?>

More on wp_query object here->

Upvotes: 1

Jiert
Jiert

Reputation: 575

Great reference: http://codex.wordpress.org/The_Loop

Just before you call the while statement, you need to query the posts. So:

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

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

EDIT: Sorry about the pagination, try this:

    <?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; ?>

Upvotes: 12

Related Questions