为Woocommerce中的特定用户角色自定义我的帐户新菜单项 [英] Custom my account new menu item for a specific user role in Woocommerce
问题描述
我为Woocommerce创建了一些自定义的我的帐户端点。我试图限制每个用户角色可见。对于以下代码,我希望它仅对具有admin角色的用户可见。我曾尝试在代码中插入条件 if(current_user_can('administrator'))
,但是没有找到不会破坏站点的方法。对如何修改以下内容有任何建议吗?
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> <p style='text-align:center;'>Test of various functions.</p>";
}
add_action( 'woocommerce_account_admin-tools_endpoint', 'add_admin_tools_content' );
推荐答案
以下是启用和显示自定义项的正确方法我的帐户菜单项仅适用于特定用户角色(此处为管理员用户角色):
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>";
}
}
代码会出现在您活跃孩子的function.php文件中主题(或活动主题)。经过测试并可以正常工作。
Code goes in function.php file of your active child theme (or active theme). Tested and work.
您将需要刷新重写规则:在Wordpress admin中的设置>永久链接下,只需单击一次保存更改按钮。大功告成
You will need to refresh rewrite rules: In Wordpress admin under "Settings" > Permalinks, just click on "Save changes" button once. You are done.
这篇关于为Woocommerce中的特定用户角色自定义我的帐户新菜单项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!