I put the code below in a single post page.
The problem is it displays correct title of the current post but incorrent count number.
It shows count 0, when the actual count is 1.
Current post has purchased=yes and firstsubmission=yest, so it should display 1.
I trid ‘post_parent’ => get_the_ID(), instead of ‘title’ => get_the_title(), and ‘posts_per_page’ => 1, but still shows count 0.
Would you please help me correct the code?
$info_args = [
'author' => get_current_user_id(),
'title' => get_the_title(),
'posts_per_page' => -1,
'post_type' => 'infosubmission',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'purchased',
'value' => 'yes',
'compare' => '=',
'key' => 'firstsubmission',
'value' => 'yes',
'compare' => '=',
)
)
];
$info_info_posts = get_posts($info_args);
$info_info_count = count($info_info_posts);
echo 'Title: ' . get_the_title() .'<br>';
echo 'Count:' .$info_info_count ;
Thank you.
2
Answers
Your meta query wrong you have to make a separate array for each meta key compare. check the below code.
If you are simple trying to get a count of all the posts belonging to a certain custom post type, just use this instead, as it’s much faster:
Unfortunately this function won’t let you filter by anything except post status, so if that’s required, then you’ll need to create a secondary query.
Firstly, you can’t query this way by title, so leave that out (it would have restricted your query to only the current post/page anyway). Second, your
meta_query
argument isn’t formatted correctly for multiple fields. Try this instead:Additionally, functions like
get_the_title()
use the global$post
object by default, so unless you provide an argument or callthe_post()
again, it will only get the title of the current page. So I’m not sure exactly what you’re trying to do here, but if you wanted to, for example, print the title of each post returned by your new query, you would need to start another loop to iterate through the results. In that case I would recommend creating a newWP_Query
independent of the main one:Note on multiple queries from the WordPress docs: