2

I have a custom column listing a post_meta value for each post in the post list screen. I could only find information on how to make a custom post type sortable. How do I make this sortable? Thanks in advance.

add_filter('manage_posts_columns' , 'ws_add_manufacturer_column');
function ws_add_manufacturer_column($defaults){
    $defaults['manufacturer'] = 'Manufacturer';
    return $defaults;
}

add_action('manage_posts_custom_column', 'ws_add_manufacturer_content', 
10, 2);
function ws_add_manufacturer_content($column_name, $post_ID) {
    if ($column_name == 'manufacturer') {
    $manufacturer_name = get_post_meta( $post_ID, 'wccaf_manufacturer', 
true );
    if ($manufacturer_name) {
        echo $manufacturer_name;
    }
    }
}

1 Answer 1

4

You need two additional functions.

The first to make the column sortable hooks into the manage_edit-{post_type}_sortable_columns filter...

function ws_sortable_manufacturer_column( $columns )    {
    $columns['manufacturer'] = 'Manufacturer';
    return $columns;
}
add_filter( 'manage_edit-post_sortable_columns', 'ws_sortable_manufacturer_column' );

and the second hooks into pre_get_posts to manipulate the query to sort by the column...

function ws_orderby_custom_column( $query ) {
    global $pagenow;

    if ( ! is_admin() || 'edit.php' != $pagenow || ! $query->is_main_query() || 'post' != $query->get( 'post_type' ) )  {
        return;
    }

    $orderby = $query->get( 'orderby' );

    switch ( $orderby ) {
        case 'manufacturer':
            $query->set( 'meta_key', 'wccaf_manufacturer' );
            $query->set( 'orderby', 'meta_value' );
            break;

        default:
            break;
    }

}
add_action( 'pre_get_posts', 'ws_orderby_custom_column' );

Hope that helps

2
  • 1
    doesnt work. mine is still sorting by some pseudo rando ordering :(
    – djack109
    Jun 1, 2020 at 15:44
  • I have integers and I got it working by replacing meta_value with meta_value_num
    – Marko
    Sep 8, 2020 at 16:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.