在WooCommerce我的帐户页面,根据特定的用户角色显示我的地址部分


On WooCommerce My account page, display My Addresses section based on specific user role

在WooCommerce My Account页面上,我试图隐藏基于用户角色的几个部分。

目前,所有直接在WooCommerce注册表单中注册的人都被分配了用户角色"Customer"。然而,只有角色为"雇主"的用户才能够进行购买……因此,我想有效地隐藏我的地址部分的用户谁是"客户"。

如果我可以用一个函数做到这一点,有什么想法吗?米罗

使用模板很容易做到这一点。将这个函数添加到您的functions.php文件中,以便您可以重用它:

function isEmployer(){
    $currentUser = wp_get_current_user();
    return in_array('employer', $currentUser->roles);
}

woocommerce > templates > myaccount中抓取my-account.php模板并复制到主题的WooCommerce目录(YOURTHEME > woocommerce > myaccount)。

从那里到第36行。这是地址被加载的地方。

用PHP if语句包装地址,如下所示:

<?php if( isEmployer() ){
        wc_get_template( 'myaccount/my-address.php' ) 
    }?>

您需要在主题中覆盖my-account.php模板,然后在一些条件逻辑中包装对地址模板的调用。特别是current_user_can(),它检查WordPress的功能。

<?php 
if( current_user_can( 'place_order' ) ){
   wc_get_template( 'myaccount/my-address.php' ); 
} ?>

理想情况下,您将基于雇主角色具有而客户角色不具有的功能来执行此操作,但在最坏的情况下,您可以使用角色名称 la current_user_can('employer')

更新2021-02-16

考虑到my-account.php的重组不再是理想的模板修改,我相信你可以通过钩子/过滤器完全删除部分,而不覆盖模板。

5.0现在已经发布了,我可能会过滤woocommerce_account_menu_items以从帐户菜单导航中删除项目。然后出于安全考虑,也从端点删除回调…作为一个示例,这将地址内容添加到地址端点:add_action( 'woocommerce_account_edit-address_endpoint', 'woocommerce_account_edit_address' );

所以要更新我的示例,如果您想完全删除某些用户的Edit Addresses选项卡,您可以使用下面的代码片段to 1。从"我的帐户"导航中删除该项目;完全禁用该端点

/**
 * Conditionally remove address menu item from My Account.
 *
 * @param array $items the My Account menu items
 * @return array
 */
function so_31342804_remove_address_from_my_account_menu( $items ) {
    // Remove menu item for users without certain capability.
    if( ! current_user_can( 'place_order' ) ) {
        unset( $items['edit-address'] );
    }
    return $items;
}
add_filter( 'woocommerce_account_menu_items', 'so_31342804_remove_address_from_my_account_menu' );

/**
 * Conditionally remove address endpoint from My Account area.
 *
 * @param array $items the My Account menu items
 * @return array
 */
function so_31342804_remove_address_endpoint( $endpoints ) {
    // Remove endpoint content for users without certain capability.
    if( ! current_user_can( 'place_order' ) ) {
        unset( $endpoints['edit-address'] );
    }
    return $endpoints;
}
add_filter( 'woocommerce_get_query_vars', 'so_31342804_remove_address_endpoint' );