Let user change posts per page

How can I allow a user to have the option of choosing the number of posts to display per page? I’d like to have it similar to how it’s done on this site: 15, 30, 50 per page (see the bottom of the page to the right of the pagination).

Related posts

Leave a Reply

2 comments

  1. This is may not be the best solution, but it works. Following code needs to be added in functions.php.

    add_filter('query_vars', 'parameter_queryvars' ); // Let WP accept the query argument we will use
    function parameter_queryvars( $qvars )
    {
        $qvars[] = 'posts_per_page';
        return $qvars;
    }
    add_action( 'pre_get_posts', 'change_post_per_page' ); // Filter posts based on passed query variable if set
    function change_post_per_page( $query ) {
        global $wp_query;
        if ( !empty($wp_query->query['posts_per_page']) && is_numeric($wp_query->query['posts_per_page'])) {
            $query->set( 'posts_per_page', $wp_query->query['posts_per_page'] );
        }
    }
    

    To print the paging, (may require changes as per your scenario)

    <div class="paging-per-post">
            <a href="http://<?php echo $_SERVER["HTTP_HOST"] . array_shift(explode('?',$_SERVER["REQUEST_URI"])) ?>?posts_per_page=15">15</a>
            <a href="http://<?php echo $_SERVER["HTTP_HOST"] . array_shift(explode('?',$_SERVER["REQUEST_URI"])) ?>?posts_per_page=30">30</a>
            <a href="http://<?php echo $_SERVER["HTTP_HOST"] . array_shift(explode('?',$_SERVER["REQUEST_URI"])) ?>?posts_per_page=50">50</a>
    </div>