Your function is unreliable and totally overboard and really really expensive. Furthermore, as already stated by @MarkKaplun, you are not calling the_post()
which causes the $post
global not to be updated to the current post being looped through, so the value from get_post_meta()
will always have the same value.
Although $post_id
might work, it is one of those crappy variables set globally that is actually used to get the comments. It is better to use get_the_ID()
or even $post->ID
as you are inside the loop. For extra info, read this post
To solve your issue, I would just create a function with a custom SQL query to fetch all unique values from a specific meta key. Here is a function I have used on another answer
/**
* Description: Getting all the values associated with a specific custom post meta key, across all posts
* Author: Chinmoy Paul
* Author URL: http://pwdtechnology.com
*
* @param string $key Post Meta Key.
*
* @param string $type Post Type. Default is post. You can pass custom post type here.
*
* @param string $status Post Status like Publish, draft, future etc. default is publish
*
* @return array
*/
function get_unique_post_meta_values( $key = '', $type="post", $status="publish" )
{
global $wpdb;
if( empty( $key ) )
return;
$res = $wpdb->get_col(
$wpdb->prepare(
"SELECT DISTINCT pm.meta_value
FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p
ON p.ID = pm.post_id
WHERE pm.meta_key = '%s'
AND p.post_status="%s"
AND p.post_type="%s"",
$key,
$status,
$type
)
);
return $res;
}
You can then just use it as follow to get an array of unique meta value
$unique_values = get_unique_post_meta_values( 'json_id' );
?><pre><?php var_dump( $unique_values ); ?></pre><?php
You can also build in some cache/transient system into the function to optimize it even more