Is it possible to count the amount of the same meta_keys for the same post_id.
I have a page with the post_id 44 and every time a user submits something on this page a new database rule is added with the meta_key "post_rating_0".
There are over 30 rules now for this page and I want to count them. For other pages the same thing.
Is this possible?
Code so far:
global $post;
$query_args = array(
'post_type' => 'page',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_key' => 'post_rating_0'
// 'fields' => 'SUM(amount_to_paid)',
);
$sum = 0;
$query = new WP_Query($query_args);
if ( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
// do the processing for each post
$sum = $sum + intval(get_post_meta(get_the_id(),'post_rating_0', true ));
}
}
echo $sum ;
This is what I got so far... But what this does is echo the value of "2" what is very logic. It searches for posts with the meta_key "post_rating_0", counts them and that are 2 posts.
What I'm trying to do is count the amount of meta_keys "post_rating_0" are in one page.
This modified code will give you an array with all post_id
and the corresponding amount of your specific meta:
$meta_arr = array();
$query = new WP_Query($query_args);
if ( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
$post_id = get_the_id();
$meta_arr[$post_id] = intval(get_post_meta($post_id, 'post_rating_0', false));
}
}
print_r($meta_arr);
Did some more research and with some modifications I managed to got it working. This is the final code:
$pagina_id_test = get_the_id();
// retrieve all meta_values with key 'post_rating_0' from database
$reviews_posts = $wpdb->get_results("
SELECT meta_value FROM " . $wpdb->prefix . "postmeta
WHERE meta_key = 'post_rating_0'
AND post_id = $pagina_id_test", ARRAY_A);
// define reviews array
$reviews_count = array();
// iterate through meta_values, count the occurence of each review
foreach ($reviews_posts as $reviews_post) {
if (isset($reviews_count[$reviews_post['meta_value']])) {
$reviews_count[$reviews_post['meta_value']] = $reviews_count[$reviews_post['meta_value']] + 1;
} else {
$reviews_count[$reviews_post['meta_value']] = 1;
}
}
// echo results
$aantal_reviews = 0;
foreach ($reviews_count as $review) {
$aantal_reviews++;
}
echo $aantal_reviews;