skip to Main Content

I would like to make a shortcode, that can be placed on category pages, for example on the sidebar.
It should display the category’s best selling products.

The only solution that I find is if I specify the category, with slug or id, like below:

[best_selling_products category=”KITCHEN-ACCESSORIES” columns=”1″ per_page=”5″]

How can I transform the shortcode to something like this?

[best_selling_products category=”CURRENT-CATEGORY” columns=”1″ per_page=”5″]

2

Answers


  1. Add this to your functions.php

    function custom_best_selling_products( $attr = array() ){
        $string = '[best_selling_products ';
        $string .= ' category="' . get_query_var( 'term' ) . '" ';
        if( $attr ){
            foreach ( $attr as $key => $value ) {
                $string .= ' ' . $key . '="' . $value . '" ';
            }
        }
        $string .= ']';
    
        return do_shortcode( $string );
    }
    
    add_shortcode( 'custom_best_selling_products', 'custom_best_selling_products' );
    

    This will create a custom shortcode and you can use it like this: [custom_best_selling_products columns="1" per_page="5"]
    This shortcode will automatically get the category

    Login or Signup to reply.
  2. Add the follows code snippet in your active theme’s functions.php to get best selling products from current $term or category page –

    function modify_woocommerce_shortcode_products_query( $query_args, $attributes, $type ) {
        if( $type != 'best_selling_products' ) return $query_args;
    
        $term = get_queried_object();
        if( $term ) {
            if( !isset($query_args['category'] ) ){
                $query_args['category'] = $term->slug;
            }
        }
        return $query_args;
    }
    add_filter( 'woocommerce_shortcode_products_query', 'modify_woocommerce_shortcode_products_query', 99, 3 );
    

    Add just use woocommerce default shortcode [best_selling_products columns="1" per_page="5"] to get the data.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search