Posted on

WooCommerce popularity and price sorting

Many WooCommerce users use search sorting that allows users to sort by popularity or price. Unfortunately while Relevanssi works fine with WooCommerce, those sorts do not work. Relevanssi doesn’t know about price or popularity, and the sorting assumes there’s default WP search underneath. Relevanssi doesn’t do meta field sorting as easily as the default WP search does.

This function handles price, popularity and rating sorting:

add_filter( 'relevanssi_orderby', 'woocommerce_relevanssi_orderby' );
function woocommerce_relevanssi_orderby( $orderby ) {
	if ( in_array( $orderby, array( 'price', 'price-desc' ), true ) ) {
		global $wp_query;
		$orderby = 'meta_value_num';
		$wp_query->query_vars['meta_key'] = '_regular_price';
	}
	if ( 'date ID' === $orderby ) {
		global $wp_query;
		$orderby = 'post_date';
	}
	if ( 'popularity' === $orderby ) {
		global $wp_query;
		$orderby = 'meta_value_num';
		$wp_query->query_vars['meta_key'] = 'total_sales';
	}
	if ( '_wc_average_rating' === $orderby ) {
		global $wp_query;
		$orderby = 'meta_value_num';
		$wp_query->query_vars['meta_key'] = 'total_sales';
	}
	return $orderby;
}

Add this to the theme functions.php. There’s bug in the current version of Relevanssi (2.1.7 for Premium, 4.0.11 for free) that prevents this from working. This will be fixed in the next version, but meanwhile you can fetch the working files from our Github repo. Here’s the correct file – replace the lib/sorting.php file with this file to make this work.

See more WooCommerce tips.

35 comments WooCommerce popularity and price sorting

  1. Hello, thanks for this. I would like to sort the search results by price ascending. I’ve added both codes from above but it doesn’t look like it’s working… Do I need to change anything in the plugin settings?
    Thanks

  2. Hi,

    The code is not working for me, is it still compatible with the latest version of WooCommerce?
    If it does, what can I be doing wrong?

    Thanks

    1. Yes, I’ve checked and it seems things have changed in WooCommerce.

      I wrote this new code for price sorting and it’s working for me:

      add_filter(‘relevanssi_hits_filter’, ‘rlv_price_sort’);
      function rlv_price_sort($hits)
      {
      if (is_search()) {
      $ordering = WC_Query::get_catalog_ordering_args();
      if (($ordering[‘orderby’] != ‘date ID’) && ($ordering[‘meta_key’] == ”)) {
      $prices = array();
      foreach ($hits[0] as $hit) {
      $price = get_post_meta($hit->ID, ‘_price’, true);
      if (!isset($prices[$price])) {
      $prices[$price] = array();
      }
      array_push($prices[$price], $hit);
      }
      $priceorder = strtolower($ordering[‘order’]);
      if ($priceorder == ‘asc’) {
      ksort($prices);
      } else {
      krsort($prices);
      }
      $sorted_hits = array();
      foreach ($prices as $price => $year_hits) {
      $sorted_hits = array_merge($sorted_hits, $year_hits);
      }
      $hits[0] = $sorted_hits;
      }
      return $hits;
      }
      }

  3. Hi Mikko,

    Great plugin, it’s been a massive help to me and my client!

    To get the price sorting working I’ve used some different code to the ones shared above, just thought I would share it in case it is useful to anyone else:

    add_filter(‘relevanssi_modify_wp_query’, ‘rlv_remove_price’);

    function rlv_remove_price($query) {

    if ( isset($_GET[‘orderby’]) &&
    $_GET[‘orderby’] == “price”) {

    global $price_sort;

    $price_sort = ‘price’;

    }elseif( isset($_GET[‘orderby’]) &&
    $_GET[‘orderby’] == “price-desc”) {

    global $price_sort;

    $price_sort = ‘price-desc’;
    }

    if ( isset($query->query_vars[‘orderby’]) &&
    $query->query_vars[‘orderby’] == “total_sales”) {

    $query->query_vars[‘orderby’] = “”;

    global $sales_sort;

    $sales_sort = true;
    }

    return $query;
    }

    The $query->get_query_vars was pulling through the incorrect values no matter what I tried, so I’ve ended up using a basic $_GET…

    For reference I haven’t changed the rlv_price_sort function.

    Hope it can be of any help!

    Kind Regards,
    Ben

  4. Hi,

    I am so lost with this. I have spent days trying to get it to work. I have made a custom sorting form that allows to sort products by Title, Date, Price low to high, Price high to low, and custom taxonomies “auteurs” and “artistes” in alphabetical order. It works great when I have Relevanssi disabled. But the price and custom taxonomies do not work when I activate the plugin. Fair enough. So I tried implementing the code here. and on this page: https://www.relevanssi.com/user-manual/relevanssi_hits_filter/ and others as well. NOTHING works. When I do a var_dump to see the query_vars it always says “relevance” when I do a price sort and it says “auteurs” or “artistes” when I sort by those custom taxonomies but the sorting is still “relevance.” If I echo $_GET[‘orderby’] I do see price and not relevance but nothing is sorted by price. Here is what I have in my functions.php file for the price sorting (I have given up on the taxonomies for now until I get price sorted!):

    add_filter(‘relevanssi_modify_wp_query’, ‘rlv_sort_by_title’);
    function rlv_sort_by_title($q) {

    if ($_GET[‘orderby’] == ‘price’) {
    $q->set(‘orderby’, ‘meta_value_num’);
    $q->set(‘post_type’, ‘product’);
    $q->set(‘meta_key’, ‘_price’);
    $q->set(‘meta_type’, ‘NUMERIC’);
    $q->set(‘order’, ‘DESC’);
    }
    else {
    $q->set(‘orderby’, ‘auteurs’);
    $q->set(‘order’, ‘DESC’);
    }

    return $q;
    }

    add_filter(‘relevanssi_modify_wp_query’, ‘rlv_remove_price’);
    function rlv_remove_price($query) {
    if (isset($query->query_vars[‘meta_key’]) && $query->query_vars[‘meta_key’] == “_price”) {
    $query->query_vars[‘meta_key’] = “”;
    global $price_sort;
    $price_sort = strtolower($query->query_vars[‘order’]);
    }
    if (isset($query->query_vars[‘meta_key’]) && $query->query_vars[‘meta_key’] == “total_sales”) {
    $query->query_vars[‘meta_key’] = “”;
    global $sales_sort;
    $sales_sort = true;
    }
    return $query;
    }

    add_filter(‘relevanssi_hits_filter’, ‘rlv_price_sort’);
    function rlv_price_sort($hits) {
    global $wp_query, $price_sort, $sales_sort;

    if (isset($price_sort)) {
    $prices = array();
    foreach ($hits[0] as $hit) {
    $price = get_post_meta($hit>ID, ‘_price’, true);
    if (!isset($prices[$price])) $prices[$price] = array();
    array_push($prices[$price], $hit);
    }

    if ($price_sort == ‘asc’) {
    ksort($prices);
    } else {
    krsort($prices);
    }

    $sorted_hits = array();
    foreach ($prices as $price => $year_hits) {
    $sorted_hits = array_merge($sorted_hits, $year_hits);
    }
    $hits[0] = $sorted_hits;
    }

    if (isset($sales_sort)) {
    $sales = array();
    foreach ($hits[0] as $hit) {
    $sale_count = get_post_meta($hit->ID, ‘total_sales’, true);
    if (!isset($sales[$sale_count])) $sales[$sale_count] = array();
    array_push($sales[$sale_count], $hit);
    }

    krsort($sales);

    $sorted_hits = array();
    foreach ($sales as $sale_count => $year_hits) {
    $sorted_hits = array_merge($sorted_hits, $year_hits);
    }
    $hits[0] = $sorted_hits;
    }

    return $hits;
    }

    Please please help! Your plugin is great and I need it cause it searches in the custom taxonomies I created which is vital. Now I just need to sort by them!

    – Helen

    1. Helen, for starters I’d recommend you make sure rlv_sort_by_title runs first. Put it on lower priority: add_filter(‘relevanssi_modify_wp_query’, ‘rlv_sort_by_title’, 9); and add_filter(‘relevanssi_modify_wp_query’, ‘rlv_remove_price’, 11);

      Now check to see that rlv_sort_by_title works right: add a var_dump($q) to the end and see that adding &orderby=price to the query sets the parameters correctly.

      If that works, next step is to see that rlv_remove_price sets the global $price_sort variable. Does it?

      If it does, then it’s time to dig in to the rlv_price_sort, but let’s leave that for later. If you take this step by step, where does the process fail?

      1. Hi Mikko,

        Really appreciate fast response! So first off rlv_sort_by_title is not running. Which is weird cause it was the first thing I added to try and fix and it worked in the beginning. I know it did cause I tested! Now I even stripped all the other codes off and put in a simple order by title:

        add_filter(‘relevanssi_modify_wp_query’, ‘rlv_sort_by_title’);
        function rlv_sort_by_title($q) {
        $q->set(‘orderby’, ‘post_title’);
        $q->set(‘order’, ‘asc’);
        return $q;
        }

        But it does not work, it does not recognize it anymore.

  5. Hi Mikko,

    Really appreciate fast response! So first off rlv_sort_by_title is not running. Which is weird cause it was the first thing I added to try and fix and it worked in the beginning. I know it did cause I tested! Now I even stripped all the other codes off and put in a simple order by title:

    add_filter(‘relevanssi_modify_wp_query’, ‘rlv_sort_by_title’);
    function rlv_sort_by_title($q) {
    $q->set(‘orderby’, ‘post_title’);
    $q->set(‘order’, ‘asc’);
    return $q;
    }

    But it does not work, it does not recognize it anymore.

      1. Hi,

        Please be patient with me. I’m not sure I’m checking correctly. I did a var_dump($search_ok) but got NULL. How do I check correctly if the filter hook is being fired?

        Thanks

        1. Try

          add_filter('relevanssi_search_ok', 'rlv_search_ok');
          function rlv_search_ok($test) {
              var_dump($test);
              exit();
          }
          1. Ok, so I get bool(false) but then I thought that maybe it might be this bit of code that I have in my functions.php file that could be causing the trouble:

            function SearchFilter($query) {
            // If ‘s’ request variable is set but empty
            if (isset($_GET[‘s’]) && empty($_GET[‘s’]) && $query->is_main_query()){
            $query->is_search = false;
            $query->is_home = true;
            }
            return $query;
            }
            add_filter(‘pre_get_posts’,’SearchFilter’);

            My advanced search has other variables apart from the “s” to search by and if someone uses it but doesn’t enter anything into the search text input the searches would always come up “No products found” until I stripped the empty “s=” from the url with the code above.

            Sure enough, when I removed that code the result for $test was bool(true) but price sorting code still doesn’t work.

  6. Relevanssi doesn’t work without a search term, so you’re not seeing any Relevanssi results if there’s no search term involved. rlv_sort_by_title() will not run, if there’s no search term.

    So, that settled, if you have a search term in use, I assume the relevanssi_search_ok test returns true? In that case, does this run and if it does, what does it print out?

    add_filter(‘relevanssi_modify_wp_query’, ‘rlv_sort_by_title’);
    function rlv_sort_by_title($q) {
    $q->set(‘orderby’, ‘post_title’);
    $q->set(‘order’, ‘asc’);
    var_dump($q->query_vars);
    return $q;
    }
    1. Ok, yeah, kind of a duhhh moment on my part. Sorry about that!
      SO, now that I’m back on track:

      I added the above code and it printed out all the variables with [“orderby”]=> string(10) “post_title” [“order”]=> string(3) “asc” . So that works.

      Then I changed ‘rlv_sort_by_title’ to my original code:

      add_filter(‘relevanssi_modify_wp_query’, ‘rlv_sort_by_title’);
      function rlv_sort_by_title($q) {

      if ($_GET[‘orderby’] == ‘price’) {
      $q->set(‘orderby’, ‘meta_value_num’);
      $q->set(‘post_type’, ‘product’);
      $q->set(‘meta_key’, ‘_price’);
      $q->set(‘meta_type’, ‘NUMERIC’);
      $q->set(‘order’, ‘DESC’);
      }
      return $q;
      }

      It printed out all the varibles with [“orderby”]=> string(14) “meta_value_num” [“order”]=> string(4) “DESC” [“meta_key”]=> string(6) “_price” . So that works.

      Then I went back to your original question: “If that works, next step is to see that rlv_remove_price sets the global $price_sort variable. Does it?”

      So I added this code:

      add_filter(‘relevanssi_modify_wp_query’, ‘rlv_remove_price’);
      function rlv_remove_price($query) {
      if (isset($query->query_vars[‘meta_key’]) && $query->query_vars[‘meta_key’] == “_price”) {
      $query->query_vars[‘meta_key’] = “”;
      global $price_sort;
      $price_sort = strtolower($query->query_vars[‘order’]);
      }
      if (isset($query->query_vars[‘meta_key’]) && $query->query_vars[‘meta_key’] == “total_sales”) {
      $query->query_vars[‘meta_key’] = “”;
      global $sales_sort;
      $sales_sort = true;
      }
      var_dump($price_sort);
      return $query;
      }

      I get: string(4) “desc” and the “meta_key” value changes to “”

      – Helen

      1. Looks like that’s working as expected, then. Next, move the rlv_price_sort(). Before this line:

        if ($price_sort == ‘asc’) {

        add

        if ($price_sort == ‘asc’) {

        That variable should contain an array with the prices as keys and the posts in arrays under the keys. Does it?

        1. Here is what I put in:

          add_filter(‘relevanssi_hits_filter’, ‘rlv_price_sort’);
          function rlv_price_sort($hits) {
          global $wp_query, $price_sort, $sales_sort;

          if (isset($price_sort)) {
          $prices = array();
          foreach ($hits[0] as $hit) {
          $price = get_post_meta($hit>ID, ‘_price’, true);
          if (!isset($prices[$price])) $prices[$price] = array();
          array_push($prices[$price], $hit);
          }

          var_dump($price_sort);
          exit();

          if ($price_sort == ‘asc’) {
          ksort($prices);
          } else {
          krsort($prices);
          }

          $sorted_hits = array();
          foreach ($prices as $price => $year_hits) {
          $sorted_hits = array_merge($sorted_hits, $year_hits);
          }
          $hits[0] = $sorted_hits;
          }

          return $hits;
          }

          Here is what is returned: string(4) “desc”

  7. I get the posts in array but do not see the prices as keys.

    array(1) { [0]=> array(3) { [0]=> object(stdClass)#12205 (24) { [“ID”]=> string(4) “5026” [“post_author”]=> string(1) “2” [“post_date”]=> string(19) “2017-12-26 14:42:04” [“post_date_gmt”]=> string(19) “2017-12-26 13:42:04” [“post_content”]=> string(1040) “Carte postale autographe signée adressée à Juliette de Serres Sur une carte postale du port de St Tropez, envoyée de La Treille Muscate, rue des Cannebiers :
    “Chère Liette, je suis ici, après un grand détour par la Bretagne, mais la plus belle Bre- tagne, îles, rochers, pêches miraculeuses. Je t’écrirai dans très peu de temps, je le jure ! Je vous embrasse tous deux tendrement. Colette”.
    Juliette de Serres épouse du compositeur Louis de Serres, Liette pour les intimes, fut la maîtresse de Willy, mari de Colette, à partir de 1900. Willy fera de leur histoire Le Maugis amoureux (Albin Michel-1905), dans lequel Liette apparaît sous les traits de madame Payet. Mais après le divorce de Colette, les deux femmes se lièrent contre Willy, notamment lors du procès que Juliette de Serres lui intentât. Ce dernier avait jouer et perdu une importante somme d’argent que Liette souhaitait investir. En 1910, il fut condamné à lui verser 5000 fr. BELLE PROVENANCE.” [“post_title”]=> string(64) “Carte postale autographe signée adressée à Juliette de Serres” [“post_excerpt”]=> string(0) “” [“post_status”]=> string(7) “publish” [“comment_status”]=> string(6) “closed” [“ping_status”]=> string(6) “closed” [“post_password”]=> string(0) “” [“post_name”]=> string(61) “carte-postale-autographe-signee-adressee-a-juliette-de-serres” [“to_ping”]=> string(0) “” [“pinged”]=> string(0) “” [“post_modified”]=> string(19) “2017-12-26 14:42:04” [“post_modified_gmt”]=> string(19) “2017-12-26 13:42:04” [“post_content_filtered”]=> string(0) “” [“post_parent”]=> string(1) “0” [“guid”]=> string(64) “https://librairie-le-pas-sage.com/?post_type=product&p=5026” [“menu_order”]=> string(1) “0” [“post_type”]=> string(7) “product” [“post_mime_type”]=> string(0) “” [“comment_count”]=> string(1) “0” [“relevance_score”]=> float(114.42) } [1]=> object(stdClass)#12206 (24) { [“ID”]=> string(4) “4806” [“post_author”]=> string(1) “1” [“post_date”]=> string(19) “2017-12-06 15:03:47” [“post_date_gmt”]=> string(19) “2017-12-06 14:03:47” [“post_content”]=> string(695) “ÉDITION ORIGINALE. UN DES 80 EXEMPLAIRES SUR PAPIER SIMILI-JAPON de couleur bleu, tirage hors-commerce réservé à l’auteur et le plus restreint (avant, 100 ex. sur Hollande et 500 ex. sur vélin). Envoi autographe signé :
    “Pour toi, mon cher Albert, encore un “bleu” Azur, azur, quand tu nous tiens… Tous mes portraient ne valent pas celui que tu signas. Je t’embrasse Colette.”
    Le destinataire est très probablement Albert Flament, journaliste proche de l’auteur et qui laissa plusieurs portraits de Colette parus dans la presse. (Nous remercions à Frédéric Maget pour cette identification)” [“post_title”]=> string(48) “Mes Apprentissages – Ce que Claudine n’a pas dit” [“post_excerpt”]=> string(97) “ÉDITION ORIGINALE. UN DES 80 EXEMPLAIRES SUR PAPIER SIMILI-JAPON. Bel envoi autographe signé.” [“post_status”]=> string(7) “publish” [“comment_status”]=> string(6) “closed” [“ping_status”]=> string(6) “closed” [“post_password”]=> string(0) “” [“post_name”]=> string(45) “mes-apprentissages-ce-que-claudine-na-pas-dit” [“to_ping”]=> string(0) “” [“pinged”]=> string(0) “” [“post_modified”]=> string(19) “2017-12-06 21:33:06” [“post_modified_gmt”]=> string(19) “2017-12-06 20:33:06” [“post_content_filtered”]=> string(0) “” [“post_parent”]=> string(1) “0” [“guid”]=> string(64) “https://librairie-le-pas-sage.com/?post_type=product&p=4806” [“menu_order”]=> string(1) “0” [“post_type”]=> string(7) “product” [“post_mime_type”]=> string(0) “” [“comment_count”]=> string(1) “0” [“relevance_score”]=> float(85.81) } [2]=> object(stdClass)#12204 (24) { [“ID”]=> string(4) “5040” [“post_author”]=> string(1) “2” [“post_date”]=> string(19) “2017-12-26 15:39:59” [“post_date_gmt”]=> string(19) “2017-12-26 14:39:59” [“post_content”]=> string(639) “ÉDITION ORIGINALE. UN DES 35 PREMIERS EXEMPLAIRES sur Japon impérial. L’ouvrage qui emprunte le titre d’un des passages du Blé en Herbe, “Ces plaisirs que l’on nomme à la légère physique”, devait s’appeler Le Fourbe, Remous ou Écumes. Colette s’explique à Hélène Picard : “Il agite des vieilles choses d’amour, se mêle des amours unisexuelles – enfin il fait ce qu’il peut”. La chair : “Sens, seigneurs intraitables, ignorants comme les princes d’autrefois qui n’apprenaient que l’indispensable : dissimuler, haïr, commande.”” [“post_title”]=> string(12) “Ces plaisirs” [“post_excerpt”]=> string(72) “ÉDITION ORIGINALE. UN DES 35 PREMIERS EXEMPLAIRES sur Japon impérial.” [“post_status”]=> string(7) “publish” [“comment_status”]=> string(6) “closed” [“ping_status”]=> string(6) “closed” [“post_password”]=> string(0) “” [“post_name”]=> string(12) “ces-plaisirs” [“to_ping”]=> string(0) “” [“pinged”]=> string(0) “” [“post_modified”]=> string(19) “2017-12-26 15:39:59” [“post_modified_gmt”]=> string(19) “2017-12-26 14:39:59” [“post_content_filtered”]=> string(0) “” [“post_parent”]=> string(1) “0” [“guid”]=> string(64) “https://librairie-le-pas-sage.com/?post_type=product&p=5040” [“menu_order”]=> string(1) “0” [“post_type”]=> string(7) “product” [“post_mime_type”]=> string(0) “” [“comment_count”]=> string(1) “0” [“relevance_score”]=> float(57.21) } } }

    1. Yes, you’re getting “0” as price for every product.

      Your problem is here:

      $price = get_post_meta($hit>ID, ‘_price’, true);

      First of all it should be $hit->ID, but if that’s just a typo here, then the problem is that the price is not stored in the custom field _price, but somewhere else.

      1. IT WORKS!!!!!!!! Thank you, thank you, thank you. You have been really supportive and patient with me and I really appreciate that. I will make sure my client makes a donation to this plugin.

        The typo in my code was $hit>ID. But I copied and pasted the code directly from this post. So look out! There is the same typo in your post above.

        Now the last thing I need to do is get my custom taxonomies to sort. I figured a good starting point is this post: https://www.relevanssi.com/user-manual/woocommerce/.

        Thought maybe I’d try the code for sorting by product category (since that is just a product taxonomy.) But that is not working:

        add_filter(‘relevanssi_modify_wp_query’, ‘rlv_include_product_cat’);
        function rlv_include_product_cat($query) {
        if (isset($query->query_vars[‘auteurs’])) {
        $query->query_vars[‘tax_query’][] = array(
        ‘taxonomy’ => ‘auteurs’,
        ‘field’ => ‘slug’,
        ‘terms’ => $query->query_vars[‘auteurs’],
        ‘include_children’ => false,
        );
        }
        return $query;
        }

        I am using the following to sort with my custom taxonomy and when there is no search query this works fine:

        add_filter(‘posts_clauses’, ‘posts_clauses_with_tax’, 10, 2);
        function posts_clauses_with_tax( $clauses, $wp_query ) {
        global $wpdb;
        //array of sortable taxonomies
        $taxonomies = array(‘auteurs’, ‘artistes’);
        if (isset($wp_query->query[‘orderby’]) && in_array($wp_query->query[‘orderby’], $taxonomies)) {
        $clauses[‘join’] .= ”
        LEFT OUTER JOIN {$wpdb->term_relationships} AS rel2 ON {$wpdb->posts}.ID = rel2.object_id
        LEFT OUTER JOIN {$wpdb->term_taxonomy} AS tax2 ON rel2.term_taxonomy_id = tax2.term_taxonomy_id
        LEFT OUTER JOIN {$wpdb->terms} USING (term_id)
        “;
        $clauses[‘where’] .= ” AND (taxonomy = ‘{$wp_query->query[‘orderby’]}’ OR taxonomy IS NULL)”;
        $clauses[‘groupby’] = “rel2.object_id”;
        $clauses[‘orderby’] = “GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC) “;
        $clauses[‘orderby’] .= ( ‘ASC’ == strtoupper( $wp_query->get(‘order’) ) ) ? ‘DESC’ : ‘ASC’;
        }
        return $clauses;
        }

        Any advice would be greatly appreciated.

        – Helen

        1. Those JOINs don’t do anything with Relevanssi; post_clauses does not trigger in the first place.

          To sort by category, you can add to the rlv_price_sort() function. The principle is the same as with the prices: for each post, check the category value, put the post in an array based on the value, then sort the array.

          Something like this:

          if (isset($wp_query->query_vars['auteurs'])) {
              $auteurs = array();
              foreach ($hits[0] as $hit) {
                  $auteur_terms = get_the_terms($hit->ID, 'auteurs');
                  if ($auteur_terms) {
                      $auteur = $auteur_terms[0];
                      if (!isset($auteurs[$auteur->name])) $auteurs[$auteur->name] = array();
                      array_push($auteurs[$auteur->name], $hit);
                  }
              }
              ksort($auteurs);
           
              $sorted_hits = array();
              foreach ($auteurs as $auteur => $hit_list) {
                  $sorted_hits = array_merge($sorted_hits, $hit_list);
              }
              $hits[0] = $sorted_hits;
          }
  8. Perfect! I had to write ‘ elseif ‘ between the two or else it wouldn’t recognize the second statement. I also included my second (AND LAST, PROMISE!) custom taxonomy ‘artistes’ with ‘elseif’ but that is not being recognized. I’m sure I’m making a small error.

    add_filter(‘relevanssi_hits_filter’, ‘rlv_price_sort’);
    function rlv_price_sort($hits) {
    global $wp_query, $price_sort, $sales_sort;

    if (isset($price_sort)) {
    $prices = array();
    foreach ($hits[0] as $hit) {
    $price = get_post_meta($hit->ID, ‘_price’, true);
    if (!isset($prices[$price])) $prices[$price] = array();
    array_push($prices[$price], $hit);
    }

    //var_dump($prices);
    //exit();

    if ($price_sort == ‘asc’) {
    ksort($prices);
    } else {
    krsort($prices);
    }

    $sorted_hits = array();
    foreach ($prices as $price => $year_hits) {
    $sorted_hits = array_merge($sorted_hits, $year_hits);
    }
    $hits[0] = $sorted_hits;
    }

    elseif (isset($wp_query->query_vars[‘auteurs’])) {
    $auteurs = array();
    foreach ($hits[0] as $hit) {
    $auteur_terms = get_the_terms($hit->ID, ‘auteurs’);
    if ($auteur_terms) {
    $auteur = $auteur_terms[0];
    if (!isset($auteurs[$auteur->slug])) $auteurs[$auteur->slug] = array();
    array_push($auteurs[$auteur->slug], $hit);
    }
    }
    ksort($auteurs);

    $sorted_hits = array();
    foreach ($auteurs as $auteur => $hit_list) {
    $sorted_hits = array_merge($sorted_hits, $hit_list);
    }
    $hits[0] = $sorted_hits;
    }

    elseif (isset($wp_query->query_vars[‘artistes’])) {
    $artistes = array();
    foreach ($hits[0] as $hit) {
    $artiste_terms = get_the_terms($hit->ID, ‘artistes’);
    if ($artiste_terms) {
    $artiste = $artiste_terms[0];
    if (!isset($artistes[$artiste->slug])) $artistes[$artiste->slug] = array();
    array_push($artistes[$artiste->slug], $hit);
    }
    }
    ksort($artistes);

    $sorted_hits = array();
    foreach ($artistes as $artiste => $hit_list) {
    $sorted_hits = array_merge($sorted_hits, $hit_list);
    }
    $hits[0] = $sorted_hits;
    }

    return $hits;
    }

    1. The code seems correct to me. With the elseif’s, it will only sort by one thing, and if both artistes and auteurs are set, it’ll be auteurs. Can that explain the problem?

      1. It seems to be working now. I’m not sure if I tested incorrectly before. The code works! Thank you so much for all your help. This is an amazing plugin and your support is better than any I’ve seen!

  9. Hi,

    The code in the post doesn’t work for me.

    I’m using the Storefront theme (by WooCommerce) with the latest version of WooCommerce.

    What can I try?

    Thanks,
    Asaf

    1. John, it’s possible WooCommerce has changed and this doesn’t work any more. The discussion with Helen here on this page has some debugging instructions you can use.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.