Custom my account new menu item for a specific user role in Woocommerce

前端 未结 1 2002
感情败类
感情败类 2020-12-20 07:01

I have created a few custom \"My Account\" endpoints for Woocommerce. I am trying to limit one to being visible per user role. For the following code, I would like it to onl

相关标签:
1条回答
  • 2020-12-20 07:43

    Here is the correct way to enable and display a custom My account menu item with it's content only for a specific user role (here "administrator" user role):

    add_action( 'init', 'add_admin_tools_account_endpoint' );
    function add_admin_tools_account_endpoint() {
        add_rewrite_endpoint( 'admin-tools', EP_PAGES );
    }
    
    add_filter ( 'woocommerce_account_menu_items', 'custom_account_menu_items', 10 );
    function custom_account_menu_items( $menu_links ){
        if ( current_user_can('administrator') ) {
            $menu_links = array_slice( $menu_links, 0,3 , true )
            + array( 'admin-tools' => __('Admin tools') )
            + array_slice( $menu_links, 3, NULL, true );
        }
        return $menu_links;
    }
    
    add_action( 'woocommerce_account_admin-tools_endpoint', 'admin_tools_account_endpoint_content' );
    function admin_tools_account_endpoint_content() {
        if ( current_user_can('administrator') ) {
            echo "<h3 style='text-align:center;'>Administration Tools</h3>
            <p style='text-align:center;'>Test of various functions.</p>";
        }
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and work.

    You will need to refresh rewrite rules: In Wordpress admin under "Settings" > Permalinks, just click on "Save changes" button once. You are done.

    0 讨论(0)
提交回复
热议问题