This query will work with Posts but the post type can be changed easily on the get_posts arguments.
/**
* 1. Register the "Posts: Most Liked" Query Type
*/
add_filter('bricks/setup/control_options', function($control_options) {
// Label updated from "Global" to "Posts: Most Liked"
$control_options['queryTypes']['posts_most_liked'] = esc_html__('Posts: Most Liked', 'snn');
return $control_options;
});
/**
* 2. Run the Query logic
*/
add_filter('bricks/query/run', function($results, $query_obj) {
if ($query_obj->object_type !== 'posts_most_liked') {
return $results;
}
// A. Fetch all standard post IDs
$posts = get_posts([
'post_type' => 'post',
'posts_per_page' => -1,
'fields' => 'ids',
'post_status' => 'publish',
]);
if (empty($posts)) return [];
// B. Count likes from your serialized array meta field (_snn_liked_by)
$count_map = [];
foreach ($posts as $post_id) {
$liked_by = get_post_meta($post_id, '_snn_liked_by', true);
$count_map[$post_id] = is_array($liked_by) ? count($liked_by) : 0;
}
// C. Sort High to Low (Descending)
arsort($count_map);
$sorted_ids = array_keys($count_map);
// D. Return the posts in the new liked order
return get_posts([
'post_type' => 'post',
'post__in' => $sorted_ids,
'orderby' => 'post__in',
'posts_per_page' => $query_obj->settings['postsPerPage'] ?? 10,
]);
}, 10, 2);
/**
* 3. Setup Post Data for Bricks Loop
*/
add_filter('bricks/query/loop_object', function($loop_object, $loop_key, $query_obj) {
if ($query_obj->object_type === 'posts_most_liked') {
global $post;
$post = $loop_object;
setup_postdata($post);
}
return $loop_object;
}, 10, 3);