I have added a custom column to the Woo orders page that displays any coupons used by the orders but I can't seem to make it sortable. I have added the column successfully and can enable sorting on the column header, but I cannot figure out how to code the sort function.
It seems from Sort coupon list column that the coupon data is not stored in the order table meta so do I need some form of join in the query to the Coupon data in the Query? If so, how is that done?
What I have so far:
Column setup
// Additional custom coupon column
add_filter( 'manage_edit-shop_order_columns', 'custom_shop_order_coupon_column', 20 );
function custom_shop_order_coupon_column( $columns ) {
$reordered_columns = array();
foreach( $columns as $key => $column){
$reordered_columns[$key] = $column;
if( $key == 'order_status' ){
$reordered_columns['coupons'] = __( 'Coupons', 'woocommerce');
}
}
return $reordered_columns;
}
// Custom column coupon content
add_action( 'manage_shop_order_posts_custom_column', 'custom_shop_order_column_coupons_content' );
function custom_shop_order_column_coupons_content( $column ) {
global $post, $the_order;
if ( ! is_a( $the_order, 'WC_Order' ) ) {
$the_order = wc_get_order( $post->ID );
}
if ( 'coupons' === $column ) {
$coupon_codes = $the_order->get_coupon_codes();
if ( ! empty($coupon_codes) ) {
echo implode(', ', $coupon_codes);
}
}
}
Then I have added the code to make it sortable like this:
// Make custom column sortable
function filter_manage_edit_shop_order_sortable_coupon_columns( $sortable_columns ) {
return wp_parse_args( array( 'coupons' => 'coupon_codes' ), $sortable_columns );
}
add_filter( 'manage_edit-shop_order_sortable_columns', 'filter_manage_edit_shop_order_sortable_coupon_columns', 10, 1 );
function action_pre_get_posts_for_coupons( $query ) {
// If it is not admin area, exit
if ( ! is_admin() ) return;
global $pagenow, $post_type;
// Compare
if ( $query->is_admin && $pagenow === 'edit.php' && $post_type === 'shop_order' && $query->get( 'orderby' ) == 'coupon_codes' ) {
// >>>>>>>>>>>>
// this won't work for coupons as not stored in order meta!!
// Get orderby
$orderby = $query->get( 'orderby' );
// Set query
if ( $orderby == 'coupon_amount' ) {
$query->set( 'meta_key', 'coupon' );
$query->set( 'orderby', 'meta_value' );
}
// <<<<<<<<<<<<<<<
}
}
add_action( 'pre_get_posts', 'action_pre_get_posts_for_coupons', 10, 1 );
Any pointers on how to order the Order list by coupon codes would be greatly appreciated. -Colin