我試圖在我的WooCommerce網站上設置自定義排序,具體而言,我想按屬性大小對所有項目進行排序。我找到了一個教程來幫助解決這個問題 - http://new.galalaly.me//2013/05/woocommerce-sort-by-custom-attributes/ - 我認爲我很好地跟蹤了它,但是它好像代碼可能過時了?WooCommerce自定義排序插件
我可以讓網站識別我的自定義排序,但它實際上並未根據大小對事物進行排序,它只是默認返回到產品名稱的字母順序。但是,它只會識別自從添加了教程中的代碼(將屬性保存到元數據以便我們可以排序)後添加或更新的項目。因此,如果項目是較舊的項目,那麼當我按大小排序時,它們甚至不會顯示在結果中。很明顯,代碼在某種程度上起作用,我似乎無法弄清楚它爲什麼不按大小進行排序。
我已經檢查過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 ***************************/