• Resolved artemis21

    (@artemis21)


    Hello,

    I’m adding a sort by featured in the products search results but I have a problem.

    This is my code:

    add_filter( ‘woocommerce_catalog_orderby’, ‘hugo_boss_catalog_orderby’ );
    sport_catalog_orderby( $orderby ) {
    // Add a new sorting option called “Featured” to the dropdown
    $orderby[‘featured’] = __(‘Featured’, ‘woocommerce’);

    // Return the modified sorting options
    return $orderby;

    }

    add_action( ‘woocommerce_product_query’, ‘sport_product_query’ );
    function sport_product_query( $q ) {
    // Check if not in admin panel and if the orderby parameter is set to “featured”
    if ( ! is_admin() && isset($_GET[‘orderby’]) && ‘featured’ === esc_attr($_GET[‘orderby’]) ) {
    // Get the existing tax queries
    $tax_query = $q->get(‘tax_query’);

    // Add a new tax query to filter by product visibility term “featured”
    $tax_query[] = array(
    ‘taxonomy’ => ‘product_visibility’,
    ‘field’ => ‘name’,
    ‘terms’ => ‘featured’,
    ‘operator’ => ‘IN’, // Include featured products
    );

    // Merge all tax queries with ‘relation’ set to ‘OR’
    $tax_query[‘relation’] = ‘OR’;

    // Add another tax query to exclude products that are marked as “featured”
    $tax_query[] = array(
    ‘taxonomy’ => ‘product_visibility’,
    ‘field’ => ‘name’,
    ‘terms’ => ‘featured’,
    ‘operator’ => ‘NOT IN’, // Exclude featured products
    );

    // Set the modified tax query
    $q->set( ‘tax_query’, $tax_query );

    // Set the order as DESC (or ASC if needed)
    $q->set( ‘order’, ‘DESC’ );
    }

    }

    unfortunately it only returns ONLY featured products, I tried adding logics to show both featured and non featured but it shows either unsorted products or no products at all.

    Can you help me fix this function so that it shows featured first and non featured after?

    Thank you

    • This topic was modified 8 months, 3 weeks ago by artemis21.
Viewing 4 replies - 1 through 4 (of 4 total)
Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Add Sort by Featured’ is closed to new replies.