php - WooCommerce:仅针对特定用户角色显示我的帐户链接
问题描述
我想在 WooCommerce 我的帐户导航中仅向特定用户角色显示订阅链接。但我不知道如何以这种方式更改导航。
我找到了更改菜单项顺序的解决方案。我找到了一个向导航添加自定义链接的解决方案。但不幸的是,我无法将这两者组合成一个工作片段。
这是更改顺序的代码:
function my_account_menu_order() {
$menuOrder = array(
'orders' => __( 'Orders', 'woocommerce' ),
'downloads' => __( 'Download', 'woocommerce' ),
'edit-address' => __( 'Addresses', 'woocommerce' ),
'edit-account' => __( 'Account Details', 'woocommerce' ),
'customer-logout' => __( 'Logout', 'woocommerce' ),
'dashboard' => __( 'Dashboard', 'woocommerce' ),
);
return $menuOrder;
}
add_filter ( 'woocommerce_account_menu_items', 'my_account_menu_order' );
因为链接在一个数组中,所以我不能if/else
用来检查用户角色。
这是向导航添加自定义链接的示例:(来自此处:https ://rudrastyh.com/woocommerce/my-account-menu.html#add_with_url )
add_filter ( 'woocommerce_account_menu_items', 'misha_one_more_link' );
function misha_one_more_link( $menu_links ){
// we will hook "anyuniquetext123" later
$new = array( 'anyuniquetext123' => 'Gift for you' );
// or in case you need 2 links
// $new = array( 'link1' => 'Link 1', 'link2' => 'Link 2' );
// array_slice() is good when you want to add an element between the other ones
$menu_links = array_slice( $menu_links, 0, 1, true )
+ $new
+ array_slice( $menu_links, 1, NULL, true );
return $menu_links;
}
add_filter( 'woocommerce_get_endpoint_url', 'misha_hook_endpoint', 10, 4 );
function misha_hook_endpoint( $url, $endpoint, $value, $permalink ){
if( $endpoint === 'anyuniquetext123' ) {
// ok, here is the place for your custom URL, it could be external
$url = site_url();
}
return $url;
}
但是订阅端点已经存在。所以我不知道如何以这种方式添加它。
有任何想法吗?
解决方案
抱歉,我找到了解决方案。
以下代码可以解决问题:
add_filter ( 'woocommerce_account_menu_items', 'misha_one_more_link' );
function misha_one_more_link( $menu_links ){
// we will hook "anyuniquetext123" later
$new = array( 'subscriptions' => __( 'Subscriptions', 'woocommerce' ), );
// or in case you need 2 links
// $new = array( 'link1' => 'Link 1', 'link2' => 'Link 2' );
// array_slice() is good when you want to add an element between the other ones
$menu_links = array_slice( $menu_links, 0, 1, true )
+ $new
+ array_slice( $menu_links, 1, NULL, true );
return $menu_links;
}
我只需要添加现有的端点。
推荐阅读
- python - 正则表达式:常量和变量字符混合的字符串
- java - 尝试获取集合时,Android Studio 不会重新设置 .collection 方法
- javascript - 三个按钮显示相同的内容。如何?
- dart - 即使构建成功且没有错误,也无法在 sublime text 3 中输出飞镖
- javascript - 如何找到动态生成的当前元素索引?
- difftime - 计算R中所有可能的“时间差”组合
- ionic-framework - 如何在 ionic 4 的浏览器(pwa)中使用社交分享插件?
- javascript - 在 JavaScript 函数中执行 Firestore 查询
- spring - Hystrix在第一次zuul调用时读取超时状态504
- python - 即使测试失败,Pytest 也会返回状态码 0