Custom my account new menu item for a specific use

2020-02-15 05:02发布

问题:

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 only be visible for a user with the admin role. I have tried inserting a conditional if (current_user_can('administrator')) into my code, but haven't found a way that doesn't break the site. Any suggestions how to modify the following?

/* Create Admin Tab on Woo Account Page
------------------------------------------------------------------*/

function add_admin_tools_endpoint() {
 add_rewrite_endpoint( 'admin-tools', EP_ROOT | EP_PAGES );
}

add_action( 'init', 'add_admin_tools_endpoint' );

function add_admin_tools_query_vars( $vars ) {
 $vars[] = 'admin-tools';
 return $vars;
}

add_filter( 'query_vars', 'add_admin_tools_query_vars', 0 );

function add_admin_tools_link_my_account( $items ) {
 $items['admnin-tools'] = 'Admin';
 return $items;
}

add_filter( 'woocommerce_account_menu_items', 'add_admin_tools_link_my_account' );

function add_admin_tools_content() {
 echo "<h3 style='text-align:center;'>Administration Tools</h3>&nbsp;<p style='text-align:center;'>Test of various functions.</p>";
}

add_action( 'woocommerce_account_admin-tools_endpoint', 'add_admin_tools_content' );

回答1:

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.