Skip to content
Advertisement

Nested shortcode to dynamically display WooCommerce products category

I am attempting to display a WooCommerce product category page based on the current user role.

I have created a custom function get_user_role() to get the user role and added the shortcode [user_role] to fetch this.

If I use the shortcode on a page it successfully returns “administrator” so I can confirm this custom shortcode is working.

I am now having trouble using this shortcode as the category slug.

So what I am trying to achieve is essentially the following:

[product_category category='[user_role]']

Advertisement

Answer

May be you are doing it in the wrong way, or may be you need to create an additional shortcode.

So the code should be something like:

if( !function_exists('prod_category') ) {

    function prod_category( $atts ) {

        // Shortcode Attributes
        $atts = shortcode_atts(
            array(
                'per_page' => '12',
                'columns' => '4',
                'orderby' => 'title',
                'order' => 'asc',
                'category' => ""
            ),
            $atts, 'prod_category'
        );

        ## User role: ##

        // 1. logged in user
        if( is_user_logged_in() ){
            $current_user = wp_get_current_user();
            $current_user_roles = $current_user->roles;
            $user_role = $current_user_roles[0]; // The user role
        } 
        else // Not logged in
        {
            // HERE set the default user role (or any product category).
            $user_role = 'visitor';
        }

        $per_page  = $atts['per_page'];
        $columns   = $atts['columns'];
        $orderby   = $atts['orderby'];
        $order     = $atts['order'];
        $category  = $user_role; // Here you can replace by your function  get_user_role();

        $output = do_shortcode ( "[product_category per_page=$per_page columns=$columns orderby=$orderby order=$order category=$category]" );

        return $output;
    }
    add_shortcode( 'prod_category', 'prod_category' );
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

SIMPLE USAGE (Example):

[prod_category]

You can also use all arguments like in the real shortcode.

This code is tested and works. You will get something like this:

enter image description here


Similar answer: WordCommerce shortcode products list

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement