【发布时间】:2021-07-15 15:36:00
【问题描述】:
我正在使用 WordPress 和 WooCommerce,我已按照这篇文章 https://rudrastyh.com/woocommerce/my-account-menu.html 在我的帐户菜单中添加新菜单项。
这是我的工作代码。
function getUserRolesByUserId( $id ) {
if ( !is_user_logged_in() ) { return false; }
$oUser = get_user_by( 'id', $id );
$aUser = get_object_vars( $oUser );
$sRoles = $aUser['roles'];
return $sRoles;
}
function createMenuBasedonUserRole($userId)
{
$userRoleIds = getUserRolesByUserId(get_current_user_id());
$urlMenuData = [];
if(!empty($userRoleIds) && in_array('mindesk_var_account',$userRoleIds)) {
$urlMenuData = [
'pageName' => "Clients",
"pageLink" => "clients"
];
} else if(!empty($userRoleIds) && in_array('mindesk_owner_account',$userRoleIds)) {
$urlMenuData = [
'pageName' => "Children",
"pageLink" => "children"
];
}
return $urlMenuData;
}
/*
* Step 1. Add Link (Tab) to My Account menu
*/
add_filter ( 'woocommerce_account_menu_items', 'mindesk_clients_children_link', 40 );
function mindesk_clients_children_link( $menu_links ){
$urlData = createMenuBasedonUserRole(get_current_user_id());
if(!empty($urlData)){
$menu_links = array_slice( $menu_links, 0, 5, true ) + array( $urlData['pageLink'] => $urlData['pageName'] ) + array_slice( $menu_links, 5, NULL, true );
}
return $menu_links;
}
/*
* Step 2. Register Permalink Endpoint
*/
add_action( 'init', 'mindesk_add_menu_endpoint' );
function mindesk_add_menu_endpoint() {
add_rewrite_endpoint( 'clients', EP_PAGES );
add_rewrite_endpoint( 'children', EP_PAGES );
}
/*
* Step 3. Content for the new page in My Account, woocommerce_account_{ENDPOINT NAME}_endpoint
*/
add_action( 'woocommerce_account_clients_endpoint', 'mindesk_clients_my_account_endpoint_content' );
function mindesk_clients_my_account_endpoint_content() {
require_once(get_template_directory() . '/myaccount/clients.php') ;
}
add_action( 'woocommerce_account_children_endpoint', 'mindesk_children_my_account_endpoint_content' );
function mindesk_children_my_account_endpoint_content() {
require_once(get_template_directory() . '/myaccount/children.php') ;
}
/* Step 4
*/
// Go to Settings > Permalinks and just push "Save Changes" button.
这就是我称为“客户”的新菜单的显示方式。
正如您在上面看到的,我添加了新菜单并执行了页面,并且基于用户角色mindesk_var_account 我需要显示clients 和mindesk_owner_account 我需要显示children。
我在/wp-content/themes/twentytwentyone/myaccount 创建了这两个 php 页面,并且工作正常。
但是,如果具有其他角色的用户尝试访问他们不允许访问的页面之一,我想使用 wp_die 或其他东西。
例如,如果登录用户具有mindesk_var_account 角色,那么如果他们尝试访问 http://localhost/wordpress/my-account/clients/ 那么我需要使用wp_die() 来不执行它。
我尝试在这两个新页面中使用wp_die,但随后执行了菜单和其他操作。我只是想要这样的东西。
我尝试使用以下代码...
add_action( 'template_redirect', 'my_account_redirect' );
function my_account_redirect() {
if( is_page( 'my-account' ) ) {
wp_die('fg');
}
}
然后它检查所有my-account 页面.. 我希望它只检查内页,如client 或children。
有人可以指导我如何实现这一目标,从这里开始我应该怎么做。
谢谢
【问题讨论】:
标签: php wordpress woocommerce endpoint user-roles