Get total posts found, but while using limit for pagination? get_posts

I have a ton of posts that I need to get the IDs of based on a custom taxonomy search. As it’s used for pagination, I also need to get the total posts without a limit, but I’m not sure how. I use the following get_posts to find them:

$args = array('posts_per_page'   => $limit,
              'offset'           => $offset,
              'category'         => '1',
              'orderby'          => 'post_date',
              'order'            => 'DESC',
              'post_type'        => 'attachment',
              'post_status'      => 'inherit',
              'suppress_filters' => true,
              'tax_query' => $search_terms, // Fairly complex search array
$attachments = get_posts($args);

But the trouble comes when I want to build a paging system based off of these results – I need to get the total posts without the limit in place. I could do the same search again and exclude $limit, but due to the sheer number of posts (300k+) it’s extremely slow especially when I only need the total number of posts and not all their information. Even get_posts seems a bit too heavy for something as simple as just getting attachment IDs.

Read More

I tried building a good old fashion MySQL query to handle it, but handling taxonomies is done so much cleaner with the above method and I couldn’t seem to get it working right.

Any advice would be greatly appreciated! Thank you!

Related posts

1 comment

  1. You can use WP_Query instead of get_posts and then you can use the properties which are set for you:

    • $post_count – The number of posts being displayed.
    • $found_posts -The total number of posts found matching the current query parameters
    • $max_num_pages – The total number of pages. Is the result of $found_posts / $posts_per_page

Comments are closed.