Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Custom Column in Wordpress Admin Pages

I'm trying to sort a custom column in the admin edit screen. The column is contains an integer value (vote counts).

To generate the column I use this "standard" code:

add_filter( 'manage_edit-entries_sortable_columns', 'cutify_entries_columns_sortable' );
function cutify_entries_columns_sortable( $columns ) 
{
    $columns['entry_vote_count'] = 'entry_vote_count';
    return $columns;
}

add_filter( 'manage_entries_posts_columns', 'cutify_entries_columns_head' );
function cutify_entries_columns_head($defaults) 
{
    unset( $defaults['date'] );
    $defaults['entry_vote_count'] = 'Votes';
    return $defaults;
}

add_action('manage_entries_posts_custom_column', 'cutify_entries_columns_content', 10, 2);
function cutify_entries_columns_content($column_name, $post_ID) 
{
    if ($column_name == 'entry_vote_count') 
    {
        $number = rand(1,1000);

        print intVal($number);
    }
}

The issue is trying to sort this column. I've read many answers here and on other sites and I do know about sorting this if the value came from post_meta, but as you can see, in this case the value comes from a return value from function call.

Is there any way of sorting a custom column not based on a post_meta value?

like image 667
John Mc Murray Avatar asked May 10 '18 06:05

John Mc Murray


People also ask

How do I modify or add custom columns to WordPress post list admin?

The filter for modifying, removing or adding columns to post list in WordPress admin panel is manage_{$post_type}_posts_columns . Exchange {$post_type} with the desired post type. For example; if you want to edit columns for post type ' post ', the filter name would be manage_post_posts_columns .

How do I add a custom field to my WordPress admin?

Adding Custom Fields in WordPress First, you need to edit the post or page where you want to add the custom field and go to the custom fields meta box. Next, you need to provide a name for your custom field and then enter its value. Click on the Add Custom Field button to save it.


1 Answers

Register A Columns First thing you need to register a column

<?php 
add_action( 'manage_cake_posts_custom_column', 'my_cake_column_content', 10, 2 );
function my_cake_column_content( $column_name, $post_id ) {
    if ( 'slices' != $column_name )
        return;
    //Get number of slices from post meta
    $slices = get_post_meta($post_id, 'slices', true);
    echo intval($slices);
} ?>

Make a Column Sortable

<?php 
 add_filter( 'manage_edit-cake_sortable_columns', 
 'my_sortable_cake_column' );
 function my_sortable_cake_column( $columns ) {
 $columns['slices'] = 'slice';

  //To make a column 'un-sortable' remove it from the array
  //unset($columns['date']);

   return $columns;
   } ?>
like image 192
Anand Choudhary Avatar answered Oct 15 '22 16:10

Anand Choudhary