Nested shortcode to dynamically display woocommerce products category

∥☆過路亽.° 提交于 2019-12-12 18:02:59

问题


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

How can I make it work?


回答1:


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:


Similar answer: WordCommerce shortcode products list



来源:https://stackoverflow.com/questions/45826950/nested-shortcode-to-dynamically-display-woocommerce-products-category

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!