【发布时间】:2016-05-29 04:49:36
【问题描述】:
我正在尝试在我的 WooCommerce 网站上设置自定义排序,特别是我想按属性 - 大小 - 对我的所有商品进行排序。我找到了一个教程来帮助解决这个问题 - http://new.galalaly.me//2013/05/woocommerce-sort-by-custom-attributes/ - 我认为我已经很好地遵循了它,但似乎那里的代码可能已经过时了?
我可以让网站识别我的自定义排序,但它实际上并没有根据大小对事物进行排序,它只是默认返回产品名称的字母顺序。但是,它仅识别自添加教程中的代码以来已添加或更新的项目(它将属性保存到元数据,以便我们可以按它排序)。因此,如果这些项目是较旧的项目,那么当我按大小排序时,它们甚至不会出现在结果中。很明显,代码在某种程度上是有效的,我似乎无法弄清楚为什么它实际上没有按大小排序。
我已经检查了 order_pa_size 是否存在于数据库中并且具有正确的顺序,并且确实如此。我确定我只是错过了一些东西,但是在尝试了我能想到的一切之后,我感到很困惑。任何帮助将不胜感激。这是我的代码 -
/************* Add sorting by attributes **************/
// Code from http://new.galalaly.me//2013/05/woocommerce-sort-by-custom-attributes/
/**
* Defines the criteria for sorting with options defined in the method below
*/
add_filter('woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args');
function custom_woocommerce_get_catalog_ordering_args( $args ) {
global $wp_query;
// Changed the $_SESSION to $_GET
if (isset($_GET['orderby'])) {
switch ($_GET['orderby']) :
case 'pa_size' :
$args['order'] = 'ASC';
$args['meta_key'] = 'pa_size';
$args['orderby'] = 'order_pa_size';
break;
endswitch;
}
return $args;
}
/**
* Adds the sorting options to dropdown list .. The logic/criteria is in the method above
*/
add_filter('woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby');
function custom_woocommerce_catalog_orderby( $sortby ) {
unset($sortby['popularity']);
unset($sortby['rating']);
unset($sortby['price']);
unset($sortby['price-desc']);
$sortby['pa_size'] = 'Sort by Size - Small to Large';
return $sortby;
}
/**
* Save custom attributes as post's meta data as well so that we can use in sorting and searching
*/
add_action( 'save_post', 'save_woocommerce_attr_to_meta' );
function save_woocommerce_attr_to_meta( $post_id ) {
// Get the attribute_names .. For each element get the index and the name of the attribute
// Then use the index to get the corresponding submitted value from the attribute_values array.
if(isset($_REQUEST['attribute_names'])){
foreach( $_REQUEST['attribute_names'] as $index => $value ) {
update_post_meta( $post_id, $value, $_REQUEST['attribute_values'][$index] );
}
}
}
/************ End of Sorting ***************************/
【问题讨论】:
标签: php wordpress sorting woocommerce