1

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.

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!

  • You're probably better off writing your own SQL as you suggested. You can run 1 SQL just to get the count and another selecting everything. WP's relational database is not that complicated. You just need to follow the ID on each table and see how they all relate. You could also make use of the $wpdb class when writing your SQL queries. codex.wordpress.org/Class_Reference/wpdb – gdaniel Mar 9 '14 at 3:10
3

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

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.