嵌套的简码可动态显示WooCommerce产品类别 [英] Nested shortcode to dynamically display WooCommerce products category

查看:102
本文介绍了嵌套的简码可动态显示WooCommerce产品类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图根据当前用户角色显示WooCommerce产品类别页面。

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

我创建了一个自定义函数 get_user_role() 来获取用户角色,并添加了简码[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]']


推荐答案

可能是您

所以代码应类似于:

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' );
}

代码包含在您活动的子主题的function.php文件中(

简单用法 (示例)

[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:

类似的答案: WordCommerce简码产品列表

这篇关于嵌套的简码可动态显示WooCommerce产品类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆