向 WooCommerce 优惠券列表中的 "code" 列添加排序

Add sorting to "code" column in WooCommerce coupon list

我正在尝试按字母和数字对优惠券代码管理栏进行排序。

我有一些优惠券仅由数字组成,而另一些则仅由字母组成。

我要展示:

基于答案代码,这是我的尝试:

function filter_manage_edit_shop_coupon_sortable_columns( $columns ) {
    // $columns['amount'] = 'amount';
    $columns['coupon_code'] = 'code';

    return $columns;
}
add_filter( 'manage_edit-shop_coupon_sortable_columns', 'filter_manage_edit_shop_coupon_sortable_columns', 10, 1 );

// Fires after the query variable object is created, but before the actual query is run.
function action_pre_get_posts( $query ) {
    // If it is not admin area, exit the filter immediately
    if( ! is_admin() ) return;

    // Get orderby
    $orderby = $query->get( 'orderby' );

    // Set query
    // if( $orderby == 'amount' ) {
        if( $orderby == 'coupon' ) {
        // $query->set( 'meta_key', 'coupon_amount' );
        $query->set( 'meta_key', 'coupon_code' );
        $query->set( 'orderby', 'meta_value_num' );
    }
}
add_action( 'pre_get_posts', 'action_pre_get_posts', 10, 1 );

虽然优惠券列是可排序的,但实际排序并未按预期进行。有什么建议吗?

$query->set( 'meta_key', '..' ) 将不起作用,因为它与元密钥无关。相反,您必须使用自定义 SQL 查询,您可以使用 $query->set( 'post__in', .. )

所以你得到:

// Make column sortable
function filter_manage_edit_shop_coupon_sortable_columns( $columns ) {
    $columns['coupon_code'] = 'code';

    return $columns;
}
add_filter( 'manage_edit-shop_coupon_sortable_columns', 'filter_manage_edit_shop_coupon_sortable_columns', 10, 1 );

// Fires after the query variable object is created, but before the actual query is run.
function action_pre_get_posts( $query ) {
    global $pagenow, $post_type, $wpdb;

    // Only for coupons
    if ( $query->is_admin && $pagenow === 'edit.php' && $post_type === 'shop_coupon' && $query->get( 'orderby' ) == 'code' ) {
        // ASC OR DESC
        $asc_desc = $query->get( 'order' );

        // Get all coupon IDs
        $coupon_ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->prefix}posts WHERE post_type = 'shop_coupon' ORDER BY post_name $asc_desc" );

        // Set
        $query->set( 'post__in', $coupon_ids );
        $query->set( 'orderby', 'post__in' );
    }
}
add_action( 'pre_get_posts', 'action_pre_get_posts', 10, 1 );

相关: