Last active
October 29, 2025 00:53
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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, | |
| )); | |
| } | |
| } | |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
end result..