CamthraX CamthraX - 6 months ago 27
PHP Question

Nested shortcode to display dynamic 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

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]']

How can I make it work?

Answer Source

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(
                '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 any plugin php file (hooks can be used in function.php file of the active theme).



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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download