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;
    }
    }
}
3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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