Last active
November 12, 2024 05:42
-
-
Save wplit/56ef1b2a7edd911353ca9c742c1482e0 to your computer and use it in GitHub Desktop.
example code for creating a new column to display number of times a post was favorited by logged in users.
This file contains 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 | |
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') { | |
// Order by the count of user IDs in the 'x_favorited_user_ids' post meta | |
$query->set('meta_key', 'x_favorited_user_count'); | |
$query->set('orderby', 'meta_value_num'); // Sort numerically by meta value (count) | |
} | |
} | |
Author
wplit
commented
Nov 12, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment