You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

针对Ultimate Member角色隐藏WooCommerce立即购买按钮报错求助

Fixing "Call to a member function get_role() on null" When Hiding WooCommerce Buy Now Button for UM Members

Hey there! Let's get that error sorted out and properly hide the WooCommerce "Buy Now" button for users with the um_member role.

Why the Error Happens

That null error pops up because the global $ultimatemember object (or its user property) isn't fully initialized when your code runs. Ultimate Member's internal user instance might not be loaded yet at the point you're checking the role, leading to that broken function call.

The Reliable Fix (Using WordPress Native Functions)

Instead of relying on UM's internal methods, use WordPress's built-in user role check—it's more stable and doesn't depend on UM's loading order. Here's how to update your code:

// First, check if the user is logged in
if ( is_user_logged_in() ) {
    // Grab the current user object
    $current_user = wp_get_current_user();
    
    // Check if the user has the 'um_member' role
    if ( in_array( 'um_member', $current_user->roles ) ) {
        // Add your logic to hide the Buy Now button here
        // For example, if you're overriding the button template, return early:
        return;
        // Or if you're using a filter, return an empty string:
        // return '';
    }
}

// If user is NOT logged in OR doesn't have the um_member role, show the button
// Your existing code to display the Buy Now button goes here

If You Still Want to Use Ultimate Member's Method

If you prefer sticking with UM's get_role() function, you need to make sure the UM object and user property exist before calling the method:

if ( is_user_logged_in() ) {
    // Access the global UM object
    global $ultimatemember;
    
    // Only proceed if the user property exists
    if ( isset( $ultimatemember->user ) ) {
        if ( $ultimatemember->user->get_role() === 'um_member' ) {
            // Hide the Buy Now button
            return;
        }
    }
}

// Show the button for non-logged-in users or non-um_member roles
// Your button display code here

Quick Notes

  • Always add this code to your child theme's functions.php file or a custom plugin—never edit core WooCommerce or Ultimate Member files (they'll get overwritten on updates).
  • Adjust the "hide" logic to match how you're rendering the button (e.g., using a filter like woocommerce_product_single_add_to_cart_text or overriding a template).

内容的提问来源于stack exchange,提问作者orlafitz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:38:29