Display Total Number of Posts per Page without Pagination in WordPress

40 Views Asked by At

I'm attempting to display a total number of posts for main categories in WordPress instead of displaying all the posts.

How do I go about limiting the total number of posts displayed without pagination?

The following doesn't work:

function target_main_category_query_with_conditional_tags( $query ) {
    if ( ! is_admin() && $query->is_main_query() ) {

        if ( is_category(array( 45, 49 )) ) {

            $query->set( 'posts_per_page', 9 );
            $query->set( 'nopaging', true );
        }
    }
}
add_action( 'pre_get_posts', 'target_main_category_query_with_conditional_tags' );
1

There are 1 best solutions below

0
Atakan Au On BEST ANSWER

This code manipulates the category page.

<?php
function target_main_category_query_atakanau( $query ) {
    if ( ! is_admin() && $query->is_main_query() && $query->is_category() && $query->get_queried_object()->parent == 0 ) {
        $query->set( 'posts_per_page', 2 );
        $query->set( 'no_found_rows', true );
        // Adds HTML to the category description:
        add_filter( 'category_description', 'add_content_to_category_description_atakanau', 10, 2);
    }
}
function add_content_to_category_description_atakanau( $description , $category_id) {
    $total_post_count = total_posts_of_category_atakanau($category_id);
    $new_description = $description . '<p>This category contains a total of '.$total_post_count.' posts.</p>';
    return $new_description;
}
function total_posts_of_category_atakanau($category_id) {
    $total_post_count = 0;

    $subcategories = get_categories( array(
        'child_of' => $category_id,
    ) );

    foreach ( $subcategories as $subcategory ) {
        $total_post_count += $subcategory->count;
    }

    // Add the post count of the given category itself
    $main_category = get_category( $category_id );
    $total_post_count += $main_category->count;

    return $total_post_count;
}
add_action( 'pre_get_posts', 'target_main_category_query_atakanau' );

Conditions:

! is_admin() : A visitor without the admin role

$query->is_category(): Category page

$query->get_queried_object()->parent == 0: The parent category

Note: as @Karl Hill said, nopaging parameter overrides posts_per_page, do not use it.