To get the number of posts you can do it easily without a second query with
$adsQuery->post_count;
But if there’s some reason (I’d love to know the context!) I can’t grasp that the same query has to be run twice and to the database directly- to answer your question as to why it’s not working:
-
Has
$table_name
been defined? Are you using{$wpdb->prefix}_posts
or{$wpdb->posts}
in$table_name
? -
You have no sql string value quotes around
$taxQuery
or$metaValue
values, so that’ll break the query, unless they integers -
Has
$wpdb
has been globally declared? -
Are you using
$wpdb->print_error()
to show the issue? -
If you echo’ed the string query instead of running it, do it look like you expect? whats missing? if you paste it in phpmyAdmin/sqlworkbench does it give you any indication of the problem?
-
do you have any errors in your servers errors logs? mysql error logs?
I would suggest something like the following
<?php
global $wpdb;
$query = "
SELECT COUNT(ID)
FROM {$wpdb->posts}
WHERE post_type="ads"
AND post_status="publish"
AND tax_query = \"%s\"
AND meta_query = \"%s\"";
// show query
// echo "<pre>{$query}</pre>";
$count = $wpdb->get_var( $wpdb->prepare(
$query,
$taxQuery,
$metaValue
));
echo "<pre>";
if($wpdb->last_error !== '') {
echo "🔥 ERROR: ";
$wpdb->print_error();
} else {
echo "Count: {$count}";
}
echo "</pre>";