1

I am trying to give users the ability to sort products on a store page by featured. I use the following code for this purpose:

add_filter( 'woocommerce_get_catalog_ordering_args', 'victor_get_catalog_ordering_args' );
function victor_get_catalog_ordering_args( $args ) {

 $orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) :  apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );

if ( 'featured' == $orderby_value ) {
    $args['orderby']  = '_featured';
    $args['order']    = 'DESC';
    $args['meta_key'] = '_featured';
}

   return $args;
}

   add_filter( 'woocommerce_default_catalog_orderby_options', 'victor_catalog_orderby' );
   add_filter( 'woocommerce_catalog_orderby', 'victor_catalog_orderby' );
   
function victor_catalog_orderby( $sortby ) {

   $sortby['featured'] = 'Featured';
   return $sortby;
}

But it doesn't work. I'm trying to sort products by featured using: /?orderby=featured But nothing is displayed, except for the message that no products were found for the request. But I know that in the admin panel I have more than 10 products marked as featured. Please help with this issue.I need to be sure to understand what I'm doing wrong.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Victor Sokoliuk
  • 435
  • 4
  • 17

1 Answers1

2

Your code is a bit outdated and deprecated since Woocommerce 3, where featured products are now set as product_visibility taxonomy for the term name featured, so this needs to be handled in a different way as follows:

add_filter( 'woocommerce_catalog_orderby', 'hugo_boss_catalog_orderby' );
function hugo_boss_catalog_orderby( $orderby ) {
    $orderby['featured'] = __('Featured', 'woocommerce');

    return $orderby;
}

add_action( 'woocommerce_product_query', 'obama_trump_product_query' );
function obama_trump_product_query( $q ) {
    if ( ! is_admin() && isset($_GET['orderby']) && 'featured' === esc_attr($_GET['orderby']) ) {
        $tax_query = $q->get('tax_query');
        $tax_query[] = array(
            'taxonomy' => 'product_visibility',
            'field'    => 'name',
            'terms'    => 'featured',
        );
        $q->set( 'tax_query', $tax_query );
        $q->set( 'order', 'DESC' ); // Or "ASC"
    }
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Related:

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • Quick note - this code shows featured products only, not "featured first and any other products after them". – Marek May 10 '22 at 07:12