如何解决在 WooCommerce 中检查挂钩功能破坏网站上的用户角色
如果存在特定用户,我正在尝试向“我的帐户”页面添加一个选项卡。
我创建了一个 check_user_role
函数来检查特定角色是否存在。
如果 premium_member
角色存在,则应在“我的帐户”页面中添加一个额外的标签。
现在,当我添加 check_user_role
函数时,它会破坏我的网站。
一切都在 functions.php
文件中
function check_user_role($roles,$user_id = null) {
if ($user_id) $user = get_userdata($user_id);
else $user = wp_get_current_user();
if (empty($user)) return false;
foreach ($user->roles as $role) {
if (in_array($role,$roles)) {
return true;
}
}
return false;
}
// ------------------
// 1. Register new endpoint (URL) for My Account page
// Note: Re-save Permalinks or it will give 404 error
function vehicle_intake_form_endpoint() {
add_rewrite_endpoint( 'vehicle-intake-form',EP_ROOT | EP_PAGES );
}
add_action( 'init','vehicle_intake_form_endpoint' );
// ------------------
// 2. Add new query var
function vehicle_intake_form_query_vars( $vars ) {
$vars[] = 'vehicle-intake-form';
return $vars;
}
add_filter( 'query_vars','vehicle_intake_form_query_vars',0 );
// ------------------
// 3. Insert the new endpoint into the My Account menu
if(check_user_role(array('premium_member'))) {
function vehicle_intake_form_link_my_account( $items ) {
$items['vehicle-intake-form'] = 'Vehicle Intake Form';
return $items;
}
add_filter( 'woocommerce_account_menu_items','vehicle_intake_form_link_my_account' );
}
// ------------------
// 4. Add content to the new tab
function vehicle_intake_form_content() {
echo '<h3>Premium WooCommerce Support</h3><p>Welcome to the WooCommerce support area. As a premium customer,you can submit a ticket should you have any WooCommerce issues with your website,snippets or customization. <i>Please contact your theme/plugin developer for theme/plugin-related support.</i></p>';
//echo do_shortcode( ' /* your shortcode here */ ' );
}
add_action( 'woocommerce_account_vehicle-intake-form_endpoint','vehicle_intake_form_content' );
解决方法
您的 If
语句需要在函数内,而不能在函数外。
您可以使用 current_user_can()
function,但内部您的钩子函数如:
add_filter( 'woocommerce_account_menu_items','vehicle_intake_form_link_my_account' );
function vehicle_intake_form_link_my_account( $items ) {
if( current_user_can('premium_member') ) {
$items['vehicle-intake-form'] = __('Vehicle Intake Form');
}
return $items;
}
或者使用 check_user_role()
重新访问的函数在您的钩子函数中使用,例如:
function check_user_role( $roles,$user_id = null ) {
$user = $user_id ? new WP_User( $user_id ) : wp_get_current_user();
if ( is_a($user,'WP_User') && count( array_intersect($roles,$user->roles) ) > 0 ) {
return true;
}
return false;
}
add_filter( 'woocommerce_account_menu_items','vehicle_intake_form_link_my_account' );
function vehicle_intake_form_link_my_account( $items ) {
if( check_user_role( array('premium_member') ) ) {
$items['vehicle-intake-form'] = __('Vehicle Intake Form');
}
return $items;
}
代码位于活动子主题(或活动主题)的functions.php 文件中。经测试有效。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。