Php 如何在电子商务中创建自定义排序
我正在创建一个自定义排序名称“price asc”,它根据最高价格对产品进行排序 我的解决办法是: 1-创建名为“\u highest\u price”的键元来存储每个产品的最高价格 2-在筛选商品目录订货人中创建自定义“价格asc” 3-过滤器参数中的自定义“orderby”、“order”、“meta\u key”\u get\u catalog\u ordering\u args functions.phpPhp 如何在电子商务中创建自定义排序,php,wordpress,sorting,woocommerce,Php,Wordpress,Sorting,Woocommerce,我正在创建一个自定义排序名称“price asc”,它根据最高价格对产品进行排序 我的解决办法是: 1-创建名为“\u highest\u price”的键元来存储每个产品的最高价格 2-在筛选商品目录订货人中创建自定义“价格asc” 3-过滤器参数中的自定义“orderby”、“order”、“meta\u key”\u get\u catalog\u ordering\u args functions.php // step 1 function my_save_post_product(
// step 1
function my_save_post_product( $post_id, $post, $update ) {
if( ! $update ) // no further actions if no changes
return;
if( $post->post_status !== 'publish' ) // no further actions if product is not public
return;
$product = wc_get_product( $post_id );
if( $product->product_type == 'variable' ) :
update_post_meta( $post_id, '_highest_price', $product->get_variation_price( 'max', true ) );
elseif( $product->product_type == 'simple' ) :
update_post_meta( $post_id, '_highest_price', $product->get_price() );
endif;
}
add_action( 'save_post_product', 'my_save_post_product', 10, 3 );
// step 2
function my_woocommerce_catalog_orderby( $options ) {
//...
$options['price-asc'] = __( 'A different low to high', 'mytheme' );
return $options;
}
add_filter( 'woocommerce_catalog_orderby', 'my_woocommerce_catalog_orderby' );
// step 3
function my_woocommerce_get_catalog_ordering_args( $args ) {
$orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
if ( $orderby_value == 'price-asc' ) :
$args['orderby'] = 'meta_value_num';
$args['order'] = 'ASC';
$args['meta_key'] = '_highest_price';
endif;
return $args;
}
add_filter( 'woocommerce_get_catalog_ordering_args', 'my_woocommerce_get_catalog_ordering_args' );
然后我去
但是,订单没有按预期显示。最高价格为“22092”的产品应在最高价格为“1177000”的产品之前显示为22092<1177000
这是我的数据库和显示器。请帮忙
过了一会儿,我终于得到了答案。我只是简单地将“价格asc”改为“价格asc”。为什么? 在
woocommerce\includes\class wc query.php中
第461行之前:$orderby_value=“price asc”
第461行:
$orderby_value = is_array( $orderby_value ) ? $orderby_value : explode( '-', $orderby_value );
在这一行之后,$orderby_值是一个数组,其中[0]=>“price”、[1]=>“asc”
第462行:
$orderby = esc_attr( $orderby_value[0] );
这一次,$orderby=“price”告诉系统在第498-501行连续运行
case 'price':
$callback = 'DESC' === $order ? 'order_by_price_desc_post_clauses' : 'order_by_price_asc_post_clauses';
add_filter( 'posts_clauses', array( $this, $callback ) );
break;
=>这是错误的$orderby不应在末尾显示为“价格”
我的建议:它可能只适用于关键字“price”,但对于未来,我们应该将排序id命名为“u”,而不是“-”。例如custom\u sort\u id
而不是custom sort id
允许您更改默认排序: