You have some minor bugs in your pre_get_posts
function, also the correct meta key is _billing_last_name
, not billing_last_name
.
So use the following instead:
- Explanation via comment tags added in the code
// Add a header
function filter_manage_edit_shop_order_columns( $columns ) {
$new_columns = array();
// Loop trough columns
foreach ( $columns as $column_name => $column_info ) {
$new_columns[ $column_name ] = $column_info;
// Compare, add after
if ( $column_name === 'order_total' ) {
$new_columns['billing_info'] = __( 'Billing info', 'woocommerce' );
}
}
return $new_columns;
}
add_filter( 'manage_edit-shop_order_columns', 'filter_manage_edit_shop_order_columns', 10, 1 );
// Populate the custom column
function action_manage_shop_order_posts_custom_column( $column, $post_id ) {
// Compare
if ( $column == 'billing_info' ) {
// Get an instance of the WC_Order object from an Order ID
$order = wc_get_order( $post_id );
// Is a WC_Order
if ( is_a( $order, 'WC_Order' ) ) {
// Get billing last name
$billing_last_name = $order->get_billing_last_name();
// NOT empty
if ( ! empty ( $billing_last_name ) ) {
echo '<p>' . $billing_last_name . '</p>';
}
}
}
}
add_action( 'manage_shop_order_posts_custom_column' , 'action_manage_shop_order_posts_custom_column', 10, 2 );
// Make custom column sortable
function filter_manage_edit_shop_order_sortable_columns( $sortable_columns ) {
return wp_parse_args( array( 'billing_info' => '_billing_last_name' ), $sortable_columns );
}
add_filter( 'manage_edit-shop_order_sortable_columns', 'filter_manage_edit_shop_order_sortable_columns', 10, 1 );
// Orderby for custom column
function action_pre_get_posts( $query ) {
// If it is not admin area, exit
if ( ! is_admin() ) return;
global $pagenow;
// Compare
if ( $pagenow === 'edit.php' && isset( $_GET['post_type'] ) && $_GET['post_type'] === 'shop_order' ) {
// Get orderby
$orderby = $query->get( 'orderby' );
// Set query
if ( $orderby == '_billing_last_name' ) {
$query->set( 'meta_key', '_billing_last_name' );
$query->set( 'orderby', 'meta_value' );
}
}
}
add_action( 'pre_get_posts', 'action_pre_get_posts', 10, 1 );
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…