2016-05-29 2 views
1

Я пытаюсь настроить пользовательский сортировку на моем сайте WooCommerce, в частности, я хочу сортировать по атрибуту - размер - по всем моим элементам. Я нашел учебник, чтобы помочь с этим - http://new.galalaly.me//2013/05/woocommerce-sort-by-custom-attributes/ - и я думал, что я следовал за ним довольно хорошо, но похоже, что код может быть устаревшим?WooCommerce Custom Sort Plugin

Я могу получить сайт для распознавания моего пользовательского сортировки, но на самом деле он не сортирует вещи по размеру, он просто по умолчанию возвращается в алфавитном порядке названия продукта. Тем не менее, он распознает только те элементы, которые были добавлены или обновлены с момента добавления кода из учебника (который сохраняет атрибуты для метаданных, чтобы мы могли сортировать их). Поэтому, если элементы являются более старыми элементами, тогда, когда я сортирую по размеру, они даже не отображаются в результатах. Настолько ясно, что код работает в некоторой степени, я просто не могу понять, почему он не сортирует по размеру.

Я проверил, что 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 ***************************/ 

ответ

0

Так для чего это стоит, это то, что я в конечном итоге делает ... это не элегантное решение, но это работает. И не изящным я имею в виду, что это уродливое, ужасное, ужасное и плохое ... но это работает, и мне нужно, чтобы он работал, поэтому я возьму его.

/************* Add sorting by 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 'size_desc' : 
       $args['order'] = 'DESC'; 
       $args['meta_key'] = 'pa_size'; 
       $args['orderby'] = 'meta_value'; 
      break; 
      case 'size_asc' : 
       $args['order'] = 'ASC'; 
       $args['meta_key'] = 'pa_size'; 
       $args['orderby'] = 'meta_value'; 
      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']); 
    unset($sortby['date']); 
    $sortby['size_desc'] = 'Sort by Size: Largest to Smallest'; 
    $sortby['size_asc'] = 'Sort by Size: Smallest to Largest'; 
    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. 
     register_taxonomy('pa_size', 
       apply_filters('woocommerce_taxonomy_objects_' . 'pa_size', array('product')), 
       apply_filters('woocommerce_taxonomy_args_' . 'pa_size', array(
        'hierarchical' => true, 
        'show_ui' => false, 
        'query_var' => true, 
        'rewrite' => false, 
       )) 
     ); 
     $size = ''; 
     if($_REQUEST['attribute_names']){ 
      $attributes = $_REQUEST['attribute_names']; 
     } else { 
      $product = new WC_Product_Simple($post_id); 
      $attributes = $product->get_attributes(); 
      foreach ($attributes as $attribute) : 
         if ($attribute['is_taxonomy']) { 
          global $wp_taxonomies; 
          $array = wc_get_attribute_taxonomies();       
          $values = wc_get_product_terms($product->id, $attribute['name'], array('fields' => 'slugs')); 
          $size = $values[0]; 
         } 
      endforeach; 
     } 
     switch(strtolower($size)): 
      case '2': 
       $new_order = 00; 
       break; 
      case '34': 
       $new_order = 01; 
       break; 
      case '56': 
       $new_order = 02; 
       break; 
      case '7': 
       $new_order = 03; 
       break; 
      case '810': 
       $new_order = 04; 
       break; 
      case '1214': 
       $new_order = 05; 
       break; 
      case 'tween': 
       $new_order = 06; 
       break; 
      case 'os': 
       $new_order = 07; 
       break; 
      case 'tc': 
       $new_order = 08; 
       break; 
      case 'xxs': 
       $new_order = 09; 
       break; 
      case 'xs': 
       $new_order = 10; 
       break; 
      case 's': 
       $new_order = 11; 
       break; 
      case 'm': 
       $new_order = 12; 
       break; 
      case 'l': 
       $new_order = 13; 
       break; 
      case 'xl': 
       $new_order = 14; 
       break; 
      case '2xl': 
       $new_order = 15; 
       break; 
      case '3xl': 
       $new_order = 16; 
       break; 
     endswitch;  
     update_post_meta($post_id, 'pa_size', $new_order); 
} 
global $sizes_fixed; 
$sizes_fixed = false; 
function sizeFixer(){ 
    global $sizes_fixed; 
    $resave = get_posts(array('post_type'=>'product', 'posts_per_page' => 500)); 
    foreach($resave as $index=>$value){ 
     save_woocommerce_attr_to_meta($resave[$index]->ID); 
    } 
    $sizes_fixed = true; 
} 
if($_REQUEST['size_fixer']){ 
    sizeFixer(); 
} 
// Function that outputs the contents of the dashboard widget 
function dashboard_widget_function($post, $callback_args) { 
    global $sizes_fixed; 
    if($sizes_fixed){ 
     echo('<p class="success">Sizes have been fixed</p>'); 
    } 
    echo "<p>Having troubles with products sorting correctly? Click the link below to reset the size order :)</p><p><a href='/wp-admin/index.php?size_fixer=true'>Fix Size Ordering</a></p>"; 
}