• Hello,

    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' );
  • The topic ‘Sort column on meta key and meta value’ is closed to new replies.