0

I'm trying to link to a specific category in my blog but limit the number of posts that are listed.

I can link to the specific category via "www.example.com/?cat=6" and after looking around the web (wordpress.org and this site) I thought I could just limit the number of posts with "www.example.com/?cat=6&showposts=5" but...

"&showposts=5" isn't returning the results that I'm expecting, am I using "showposts" correctly? Is there something better?

If not how can I build my url to only show a specific number of posts?

While I have access to the theme and the loop, I would prefer not to edit that and not install some plugin, my feed is perfect, I'd just like to build a link for this one type of use case.

0

showposts is an alias of posts_per_page, which is a private query var, meaning it can't be set from the query string. You could register your own query var and map that to posts_per_page in a pre_get_posts action. This could go in your theme's functions.php and would work for any main query.

// add a new query var to the list of known query vars
function wpd_custom_posts_queryvar( $vars ){
    $vars[] = 'wpd-num';
    return $vars;
}
add_filter( 'query_vars', 'wpd_custom_posts_queryvar' );

// hook pre_get_posts and set posts_per_page
// if it's the main query and our custom query var is set 
function wpd_custom_posts_number( $query ){
    if( $query->is_main_query() && $query->get( 'wpd-num' ) ){
        $query->set( 'posts_per_page', $query->get( 'wpd-num' ) );
    }
}
add_action( 'pre_get_posts', 'wpd_custom_posts_number' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.