Skip to content

Instantly share code, notes, and snippets.

@wplit
Last active October 29, 2025 00:53
Show Gist options
  • Select an option

  • Save wplit/1efda5bb407726e65df08ca9636d978e to your computer and use it in GitHub Desktop.

Select an option

Save wplit/1efda5bb407726e65df08ca9636d978e to your computer and use it in GitHub Desktop.
add column to show number of user accounts that have favorited each post (the default 'post' post type) see screenshot in comment below code for end result.
<?php
// Add a custom column to display favorite count of each post
add_filter('manage_post_posts_columns', 'add_favorited_users_column');
function add_favorited_users_column($columns) {
$columns['favorited_users'] = 'Favorited Count';
return $columns;
}
// Display the count in our custom column
add_action('manage_post_posts_custom_column', 'show_favorited_users_column_content', 10, 2);
function show_favorited_users_column_content($column, $post_id) {
if ( $column == 'favorited_users' ) {
echo bricksextras_post_favorite_count( $post_id );
}
}
// Optional / make column sortable
add_filter('manage_edit-post_sortable_columns', 'register_favorited_users_sortable_column');
function register_favorited_users_sortable_column($sortable_columns) {
$sortable_columns['favorited_users'] = 'favorited_users';
return $sortable_columns;
}
// Modify query to sort by the "Favorited Count" column - the x_favorite_users_count
add_action('pre_get_posts', 'sort_by_favorited_users_column');
function sort_by_favorited_users_column($query) {
if (!is_admin() || !$query->is_main_query()) {
return;
}
// Check if we're sorting by the "Favorited Count" column
if ($query->get('orderby') === 'favorited_users') {
// Get the current order direction
$order = strtoupper($query->get('order')) === 'ASC' ? 'ASC' : 'DESC';
// Set a meta query
$query->set('meta_query', array(
'favorite_count_clause' => array(
'key' => 'x_favorite_users_count',
'compare' => 'EXISTS',
'type' => 'NUMERIC',
),
'relation' => 'OR',
array(
'key' => 'x_favorite_users_count',
'compare' => 'NOT EXISTS',
),
));
// Order by our named clause
$query->set('orderby', array(
'favorite_count_clause' => $order,
));
}
}
@wplit
Copy link
Author

wplit commented Oct 29, 2025

end result..

SCR-20251029-kdgv

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment