I'm trying to do a count for pagination and its returning NULL why the query returns results correctly. In this case $total returns NULL which is not correct why? (I didn't include the $args as they work)

$total_query = "SELECT COUNT(*) FROM (${args}) AS total_count";
$total = $wpdb->get_var( $total_query );
$items_per_page = 5;
$page = isset( $_GET['cpage'] ) ? abs( (int) $_GET['cpage'] ) : 1;
$offset = ( $page * $items_per_page ) - $items_per_page;
$results = $wpdb->get_results( $args . " ORDER BY user_registered DESC   LIMIT ${offset}, ${items_per_page}" );

In your code it is actually counting the query you have inserted in $testargs. In your case you entered one. So it is giving you back one. If you need to get the count on WordPress users table then write the query like below-

global $wpdb;

$total_query = "SELECT COUNT(*) FROM {$wpdb->users} AS total_count";
$total = $wpdb->get_var( $total_query );

i think you code snippet should look something like below code snippet in your code i am not getting why you are adding the same query again in $total_query by appending $testargs so try the below code snippet that should work for you.

$total_query = "SELECT COUNT(*) FROM {$wpdb->users}";
$total = $wpdb->get_var( $total_query );
echo $total;

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.