Skip to content
Advertisement

Add a sortable custom column in Woocommerce Admin Orders list

I’ve added a custom column to the “Orders” section of WooCommerce for the shipping zip code. The column and its values appear correctly.

What I cannot figure out is how to make the sorting of this field work (clicking on the column header). Other code examples I could find mention using the hook “manage_edit-shop_order_sortable_columns”, but this doesn’t seem to be working for this field.

Note: I’ve seen the other StackOverflow issues about this, but none seem to have sorting working.

/**
 * ADD ZIP CODE TO WOOCOMMERCE ORDERS LIST
 */

// Add column (working)
add_filter( 'manage_edit-shop_order_columns', 'custom_woo_columns_function' );
function custom_woo_columns_function( $columns ) {
    $new_columns = ( is_array( $columns ) ) ? $columns : array();
    unset( $new_columns[ 'order_actions' ] );

    // all of your columns will be added before the actions column
    $new_columns['zipcode'] = 'Zip Code';

    //stop editing
    $new_columns[ 'order_actions' ] = $columns[ 'order_actions' ];
    return $new_columns;
}

// Change order of columns (working)
add_action( 'manage_shop_order_posts_custom_column', 'custom_woo_admin_value', 2 );
function custom_woo_admin_value( $column ) {
    global $post;
    $zip_value = get_post_meta($post->ID, '_shipping_postcode', true);
    if ( $column == 'zipcode' ) {
        echo ( isset( $zip_value ) ? $zip_value : '' );
    }
}

// Sort by custom column (NOT WORKING)
add_filter( "manage_edit-shop_order_sortable_columns", 'custom_woo_admin_sort' );
function custom_woo_admin_sort( $columns )
{
    $custom = array(
        'zipcode'    => '_shipping_postcode',
    );
    return wp_parse_args( $custom, $columns );
}

Advertisement

Answer

I figured it out. Will leave this up here for anyone else trying to add a sorted zip code column. Just add this additional action.

// Make sorting by custom column work properly
add_action('pre_get_posts', 'custom_zipcode_orderby');
function custom_zipcode_orderby($query)
{
    if (!is_admin()) return;
    
    $orderby = $query->get('orderby');
    if ('_shipping_postcode' == $orderby) {
        $query->set('meta_key', '_shipping_postcode');
        $query->set('orderby', 'meta_value_num');
    }
}

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement