wordpress - 按产品尺寸(长度、宽度和高度)排序的 Wordpress (Woocommerce)
问题描述
我正在尝试按长度和宽度订购我的产品,首先按长度排序,如果两个产品具有相同的值,它将按宽度排序(依此类推)。如果我能先让它工作,我想增加高度。
到目前为止,我遇到的问题是它按长度和仅按长度订购产品(加上一个错误,即使长度不正确,即产品订单是 2.1、2 和 2.5)。
这是我从查询中得到的:
function woocommerce_catalog_orderby( $args ) {
$args['meta_query'] = array(
'relation' => 'AND',
'length_clause' => array(
'key' => '_length',
'type' => 'DECIMAL',
'orderby' => 'meta_value_num',
),
'width_clause' => array(
'key' => '_width',
'type' => 'DECIMAL',
'orderby' => 'meta_value_num',
),
);
$args['orderby'] = array(
'length_clause' => 'ASC',
'width_clause' => 'ASC',
);
return $args;
}
add_filter('woocommerce_get_catalog_ordering_args', 'woocommerce_catalog_orderby');
我确信我错过了一些我目前看不到的明显东西。任何帮助深表感谢!
解决方案
在您的情况下,您必须在为 woocommerce 添加过滤器时添加优先级。这是按元值排序的工作代码:
/**
- 保存产品时保存产品属性以发布元数据。
- @param int $post_id 帖子 ID。
- @param post $post 帖子对象。
- @param bool $update 这是否是正在更新的现有帖子。
- 来源:https ://www.webhat.in/article/woocommerce-tutorial/custom-order-by-attributes/
- 参考:https ://codex.wordpress.org/Plugin_API/Action_Reference/save_post/ */
'''
function wh_save_product_custom_meta($post_id, $post, $update) {
$post_type = get_post_type($post_id);
// If this isn't a 'product' post, don't update it.
if ($post_type != 'product')
return;
if (!empty($_POST['attribute_names']) && !empty($_POST['attribute_values'])) {
$attribute_names = $_POST['attribute_names'];
$attribute_values = $_POST['attribute_values'];
foreach ($attribute_names as $key => $attribute_name) {
switch ($attribute_name) {
//for color (string)
case 'pa_color':
//it may have multiple color (eg. black, brown, maroon, white) but we'll take only the first color.
if (!empty($attribute_values[$key][0])) {
update_post_meta($post_id, 'pa_color', $attribute_values[$key][0]);
}
break;
//for lenght (int)
case 'pa_length':
if (!empty($attribute_values[$key][0])) {
update_post_meta($post_id, 'pa_length', $attribute_values[$key][0]);
}
break;
default:
break;
}
}
}
}
add_action( 'save_post', 'wh_save_product_custom_meta', 10, 3);
'''
推荐阅读
- laravel - Selenium 的黄昏无法与 Laradock 一起使用
- java - DataInputStream read() 总是返回 -1
- c - 如何存储字符串直到找到空格
- c# - 更灵活的 Assert.ThrowsException?
- hive - SAS Hive 中的时间戳转换失败
- android - Android 应用程序:此 IP、站点或移动应用程序无权使用此 API 密钥
- python - 如何在 jupyter notebook 中设置日期时间列的格式
- javascript - 在构造函数中定义自定义元素的生命周期回调
- python - 我可以通过带有 LinearRegressor 的钩子记录训练损失吗?
- c# - 如何在 Visual Studio 中的对象初始化的“新”行上有 {