Anatoliy Osmolovskii
Anatoliy Osmolovskii

Reputation: 33

Extend WooCommerce Product Filters plugin shortocodes

I am using Woocommerce with WOOF plugin (woocommerce filter). In particular, this plugin can display a filter that will only search in a specific product category using for example [woof taxonomies=product_cat:23] shortcode and display the results using the [woof_products taxonomies=product_cat:23] shortcode, where 23 is the category id of goods.

However, it is not always possible to specify a category in the shortcode itself, and I would like to implement functionality that allows you to use a shortcode like [woof taxonomies=product_cat:auto], which will automatically determine the current category using a specific function, for example, this (the function is tested and works):

function show_product_category_id() {
    $cat = get_queried_object();
    $catID = $cat->term_id;
    if (empty($catID)) {
        //
        if (strpos($_GET['really_curr_tax'], 'product_cat')) {
            $catID=str_replace('-product_cat', '', $_GET['really_curr_tax']);
        }
        else {}
    }
    else {}
    echo $catID;
}

I can, of course, create a shortcode for this function, and add it to the theme's functions.php:

add_shortcode( 'show_product_category_id', 'show_product_category_id' );

and it will work. But I can't use a construction like:

[woof taxonomies=product_cat:[show_product_category_id]]

since nested shortcodes in Wordpress won't work. Therefore, apparently, I need to add to woocommerce the ability to specify not only product_cat:35, but also product_cat:auto.

How can i realize it? Or, is there also a way to use nested shortcodes in wordpress?

Upvotes: 2

Views: 1194

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253921

Of course that you can't nest shortcodes one in another, but what you can do is embed a shortcode in a another shortcode as follows:

function woof_current_product_category_id() {
    $term    = get_queried_object();
    $term_id = 0; // Initializing

    if ( isset($_GET['really_curr_tax']) && false !== strpos( $_GET['really_curr_tax'], 'product_cat' ) ) {
        $term_id = (int) str_replace('-product_cat', '', $_GET['really_curr_tax']);
    } elseif ( is_a($term, 'WP_Term') ) {
        $term_id = (int) $term->term_id;
    }
    return do_shortcode("[woof taxonomies=product_cat:$term_id]"); // Always use return for a shortcode
}
add_shortcode( 'show_product_category_id', 'woof_current_product_category_id' );

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

So the usage will simply be: [show_product_category_id]

Upvotes: 3

Related Questions