2

Is it possible in Wordpress to return the total number of results from $wpdb->get_results ignoring the limit?

Example:

$datas = $wpdb->get_results("
  SELECT DISTINCT wp_posts.ID, wp_posts.post_title, wp_posts.post_excerpt FROM wp_posts
  INNER JOIN wp_postmeta ON
    wp_posts.ID = wp_postmeta.post_id
    WHERE (
            wp_posts.post_title LIKE '%hello%' OR
            wp_postmeta.meta_value LIKE '%hello%'
          )
          AND wp_posts.post_status = 'publish'
          AND wp_posts.post_type IN ('post', 'page')

    ORDER BY wp_posts.post_date DESC
    LIMIT 0, 24
", ARRAY_A);

Or would I need to run two queries, one with count(*) for the total number of posts and then another as the above query to get the actual post content?

2
  • So you only want to have count(*) in your results? Commented Jun 20, 2018 at 11:21
  • @revo, I'd like to return 24 posts at a time but I'd like to know what the total count is without the limit as well, so I was wondering if that can be done in one query or would I need to run two queries Commented Jun 20, 2018 at 11:24

1 Answer 1

1

You could include SQL_CALC_FOUND_ROWS option in your select query:

SELECT SQL_CALC_FOUND_ROWS ...

Then invoke FOUND_ROWS() immediately:

SELECT FOUND_ROWS();

However, it's up to you to compare performing time of running a separate query over using SQL_CALC_FOUND_ROWS option. Sometimes the former outperforms the latter.

Sign up to request clarification or add additional context in comments.

7 Comments

How would I go about incorporating this functionality into $wpdb->get_results?
After adding that option to your current select query, you would do $wpdb->get_results( "SELECT FOUND_ROWS()" );
I tried this but when I add SQL_CALC_FOUND_ROWS to the first query, it returns nothing
Did you call FOUND_ROWS() afterward?
Adding SQL_CALC_FOUND_ROWS to the select query SHOULD NOT return anything. You have the number of total rows just after invoking FOUND_ROWS() function. Please read manual. I'm not sure about wordpress get_results method. There may be something wrong with it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.