[SOLVED] How to add a shortcode on a specific page based on the url parameter

Issue

I would like to add a custom content before the WooCommerce shop loop if a specific filter is active.

The example url is this: /shop/?filter_brand=nike

So far I have tried with this:

add_action( 'woocommerce_before_shop_loop', 'amc_add_content_before_loop' );
function amc_add_content_before_loop() {
    if ( is_product_category('nike') ) {
        echo esc_html__("Custom content", "amc");
    }
}

But the content is not shown on the page.

EDIT

With Vincenzo’s answer now it works.
I am now trying to use variables and add a shortcode. I tried with this:

add_action( 'woocommerce_before_shop_loop', 'add_custom_content_before_shop_loop2' );
function add_custom_content_before_shop_loop2() {
    $terms = get_terms( 'pa_brand' );
    foreach ( $terms as $term ) {
        if ( is_shop() && isset( $_GET['filter_brand'] ) && $_GET['filter_brand'] == $term->name ) {
            echo do_shortcode('[block id="brand-'.$term->name.'"]');
        }
    }
}

So what it supposed to do is, if a filter $term->name is active, a custom shortcode with the $term->name should be echoed.

But it’s not working.

Solution

Considering the url you posted: /shop/?filter_brand=nike, you can do it like this:

add_action( 'woocommerce_before_shop_loop', 'add_custom_content_before_shop_loop' );
function add_custom_content_before_shop_loop() {

    if ( is_shop() && isset( $_GET['filter_brand'] ) && $_GET['filter_brand'] == 'nike' ) {
        // add custom content
    }

}

The code has been tested and works. Add it to your active theme’s functions.php file.

EDIT

To get the pa_brand attribute name you are using $term->name instead of $term->slug.

$term is an instance of the WP_Term class. The structure of the WP_Term object can be found here.

Try with this:

add_action( 'woocommerce_before_shop_loop', 'add_custom_content_before_shop_loop2' );
function add_custom_content_before_shop_loop2() {
    $terms = get_terms( 'pa_brand' );
    foreach ( $terms as $term ) {
        if ( is_shop() && isset( $_GET['filter_brand'] ) && $_GET['filter_brand'] == $term->slug ) {
            echo do_shortcode('[block id="brand-'.$term->slug.'"]');
        }
    }
}

Answered By – Vincenzo Di Gaetano

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published.