0

In the WordPress backend I'd like to sort a custom post type column on a meta key and meta value.

The meta key is called 'status'. I've got three different meta value's for the 'status' key. How can I sort them alphabetically?

This is my code:

// Register the column
function status_column_register( $columns ) {
    $columns['status'] = __( 'status', 'bf_rapportage' );

    return $columns;
}
add_filter( 'manage_edit-bf_rapportage_columns', 'status_column_register' );

// Display the column content
function status_column_display( $column_name, $post_id ) {
    if ( 'status' != $column_name )
        return;

    $status = get_post_meta($post_id, 'status', true);
    if ( !$status )
        $status = '<em>' . __( 'undefined', 'bf_rapportage' ) . '</em>';

    echo $status;
}
add_action( 'manage_posts_custom_column', 'status_column_display', 10, 2 );

// Register the column as sortable
function status_column_register_sortable( $columns ) {
    $columns['status'] = 'status';

    return $columns;
}
add_filter( 'manage_edit-bf_rapportage_sortable_columns', 'status_column_register_sortable' );

function status_column_orderby( $vars ) {
    if ( isset( $vars['orderby'] ) && 'status' == $vars['orderby'] ) {
        $vars = array_merge( $vars, array(
            'meta_key' => 'status',
            'orderby' => 'meta_value_num'
        ) );
    }

    return $vars;
}
add_filter( 'request', 'status_column_orderby' );
1

Have you tried changing your orderby value to meta_value, rather than meta_value_num in your status_column_orderby function? This has always worked for me in the past. I'm assuming we are dealing with words, not numbers, since you said "alphabetically" in your question. meta_value is for letters/characters, with meta_value_num reserved for... you guessed it... numbers.

1
  • Hello @Strap1 Thanks for your answer, this helped me out! – Mick D Jan 6 '14 at 15:39

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.