Skip to content

Instantly share code, notes, and snippets.

@kylephillips
Created September 2, 2015 19:11
Show Gist options
  • Save kylephillips/dd81584e30b35a74d632 to your computer and use it in GitHub Desktop.
Save kylephillips/dd81584e30b35a74d632 to your computer and use it in GitHub Desktop.
Add favorite counts to the WP admin post tables
<?php
// Place this code in your theme's functions.php file
/**
* First, add the column to the view
* Change the post type by substituting 'post' with the post type
* Ex: a post type of recipe would be manage_recipe_posts_columns
*/
add_filter('manage_post_posts_columns', 'add_favorite_count_column');
function add_favorite_count_column($columns)
{
$new_column = array('favorites' => __('Favorites'));
return array_merge($columns, $new_column);
}
/**
* Next, add the column data
*/
add_action('manage_posts_custom_column', 'add_favorites_data_to_column', 10, 2);
function add_favorites_data_to_column($column, $post_id)
{
if ( $column !== 'favorites' ) return;
echo get_favorites_count($post_id);
}
?>
@essaysnark
Copy link

essaysnark commented Mar 5, 2017

This sorta works for getting a sortable column... If a post has not been favorited then it won't appear in the sorted view


/**
* Now make that new column sortable
*/

add_filter( 'manage_edit-post_sortable_columns', 'my_sortable_favorites_column' );
function my_sortable_favorites_column( $columns ) {
    $columns['favorites'] = 'favorite';
 
    //To make a column 'un-sortable' remove it from the array
    //unset($columns['date']);
 
    return $columns;
}

/**
* And finally, tell it what to sort on
*/

add_action( 'pre_get_posts', 'my_favorite_orderby' );
function my_favorite_orderby( $query ) {
    if( ! is_admin() )
        return;
 
    $orderby = $query->get( 'orderby');
 
    if( 'favorite' == $orderby ) {

	$query->set('meta_key','simplefavorites_count');
        $query->set('orderby','meta_value_num');
    }
}


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