嵌套短代码,动态显示woocommerce产品类别

时间:2017-08-22 21:04:52

标签: php wordpress woocommerce categories shortcode

我正在尝试根据当前用户角色显示woocommerce产品类别页面。我创建了一个自定义函数 get_user_role() 来获取用户角色,并添加了短代码[user_role]来获取它。如果我在页面上使用短代码,它会成功返回“管理员”,这样我就可以确认这个自定义短代码是否正常工作。

我现在无法使用此短代码作为类别slug。

所以我想要实现的目标基本上如下:

[product_category category='[user_role]']

我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:2)

可能是你做错了,或者你需要创建一个额外的短代码。

所以代码应该是这样的:

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]
  

您还可以使用所有参数,例如真正的短代码。

此代码已经过测试并且有效。你会得到这样的东西:

enter image description here

类似的答案:WordCommerce shortcode products list

相关问题