如何使 woo 产品视图中的自定义列可排序?

how to make custom column in woo products view sortable?

我正在尝试在 WooCommerce 产品列表视图中添加新的自定义列。

我已经创建了列并填充了数据,但是我在排序时遇到了问题table?

如何在 table 列表中使此自定义列排序 table?

谢谢

// 向 Woo Products Admin Dash 添加新列

function woo_product_rmreference_column( $columns ) {
    $columns['rm_reference'] = esc_html__( 'Reference ID', 'woocommerce' );
        return $columns;
}
add_filter( 'manage_edit-product_columns', 'woo_product_rmreference_column', 2 );

// 填充列

function woo_product_rmreference_column_data( $column ) {
    global $post;

    if ( $column == 'rm_reference' ) {
            
            // Product
            $product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
            
            // Get ACF Fields
            $reference = get_field( 'rightmove_property_reference', $product_id );

            // Output
            echo ($reference) ? '<div>'.$reference.'</div>';
    }
}
add_action( 'manage_product_posts_custom_column' , 

// 生成 Sortable

function product_rmreference_column_width_query( $query )
    {
        $orderby = $query->get( 'orderby' );
        if ( 'rm_reference' == $orderby ) {
            $meta_query = array(
                'relation' => 'OR',
                array(
                    'key' => '_ref',
                    'compare' => '>', 
                ),
                array(
                    'key' => '_ref',
                ),
            );

            $query->set( 'meta_query', $meta_query );
            $query->set( 'orderby', 'meta_value' );
        }
    }
add_action( 'pre_get_posts', 'product_rmreference_column_width_query' );

您仍然需要在管理中将该列添加为可排序。然后我也会让你的 pre_get_posts 查询将 _ref 评估为 NUMERIC

// ADD THIS.
add_filter( 'manage_edit-product_sortable_columns', 'my_sortable_reference_column' );
function my_sortable_reference_column( $columns ) {
    $columns['rm_reference'] = 'reference_id';
    return $columns;
}

function product_rmreference_column_width_query( $query ) {
    if ( is_admin() ) {
        $orderby = $query->get( 'orderby' );
        // I changed this to 'reference_id' to match the column sort.
        if ( 'reference_id' == $orderby ) {
            $meta_query = array(
                'relation' => 'OR',
                array(
                    'key'     => '_ref',
                    'compare' => '>',
                    'type' => 'NUMERIC'
                ),
                array(
                    'key' => '_ref',
                ),
            );
            
            $query->set( 'meta_query', $meta_query );
            $query->set( 'orderby', 'meta_value' );
        }
    }
}

add_action( 'pre_get_posts', 'product_rmreference_column_width_query' );