How to order by post meta name in wp admin?

I assume merchant name is another meta field and not the title for that post type? If so, here is a way to organize your admin edit.php area

// Add a column in admin edit.php to display the Merchant post type data you want shown
add_filter('manage_merchant_posts_columns', 'admin_merchant_columns');
function admin_merchant_columns( $posts_columns ) {
    $posts_columns = array(
        'cb' => '<input type="checkbox" />', // the checkbox to select the line item
        'title' => __( 'Name' ), // post title
        'merchant_name' => __( 'Merchant Name' ), // where merchant_name is your meta key for that field
        '_merchant_id' => __( 'Merchant ID' ) // merchant id meta key
    );

    return $posts_columns;
}

// Fill the column with the appropriate items
add_action( 'manage_merchant_posts_custom_column', 'manage_merchant_columns', 10, 2 );
function manage_merchant_columns( $column, $post_id ) {
    global $post;
    switch( $column ) {
        case 'merchant_name' :
            $merchant_name = get_post_meta( $post_id, 'merchant_name'); 
            if ( empty( $merchant_name ) )
                echo ( '' );
            else
                print join( $merchant_name, ', ' );

            break;
        case '_merchant_id' :
            $_merchant_id = get_post_meta( $post_id, '_merchant_id'); 
            if ( empty( $_merchant_id ) )
                echo ( '' );
            else
                print join( $_merchant_id, ', ' );

            break;

        default :
            break;
    }
}

// add ability to sort by merchant name
add_filter( 'manage_edit-merchant_sortable_columns', 'sort_by_merchant_name' );
function sort_by_merchant_name( $columns ) {
    $columns['merchant_name'] = 'merchant_name';
    return $columns;
}

add_action( 'load-edit.php', 'sort_by_merchant_name_load' );
function sort_by_merchant_name_load() {
    add_filter( 'request', 'sort_merchant' ); // where "merchant" is your custom post type slug
}

function sort_merchants( $vars ) {
    if ( isset( $vars['post_type'] ) && 'merchant' == $vars['post_type'] ) { // where "merchant" is your custom post type slug
        if ( isset( $vars['orderby'] ) && 'merchant_name' == $vars['orderby'] ) {
            $vars = array_merge(
                $vars,
                array(
                    'meta_key' => 'merchant_name',
                    'orderby' => 'meta_value'
                )
            );
        }
    }
    return $vars;
}

Leave a Comment

error code: 523