Add Custom Price On user role In Woocommerce Using ACF

To add custom prices based on user roles in WooCommerce using Advanced Custom Fields (ACF), you can follow these steps:

Step 1: Install and Activate ACF Plugin Make sure you have the ACF plugin installed and activated on your WordPress site.

Step 2: Create ACF Field Group for Custom Prices In the WordPress admin panel, go to Custom Fields > Add New and create a new Field Group with your desired settings. Add a Repeater field to store custom prices for different user roles. Each repeater item will have two fields: one for the user role and another for the custom price.

Step 3: Add Custom Prices for User Roles Edit each product and enter the custom prices for different user roles using the ACF repeater field you created in Step 2.

Step 4: Apply Custom Prices Based on User Role To apply the custom prices based on the user’s role, you’ll need to hook into the woocommerce_product_get_price filter. This filter allows you to modify the product price before it’s displayed.

Add the following code to your theme’s functions.php file or a custom plugin:

function custom_product_price_based_on_user_role( $price, $product ) {
    // Get the current user role
    $current_user = wp_get_current_user();
    $user_roles = $current_user->roles;

    // Get the ACF repeater field data
    $custom_prices = get_field( 'custom_prices', $product->get_id() );

    if ( $custom_prices ) {
        foreach ( $custom_prices as $item ) {
            $role = $item['user_role'];
            $custom_price = (float) $item['price'];

            if ( in_array( $role, $user_roles ) ) {
                return $custom_price;
            }
        }
    }

    // If no custom price is found for the user role, return the original price
    return $price;
}
add_filter( 'woocommerce_product_get_price', 'custom_product_price_based_on_user_role', 10, 2 );

This code will check the current user’s role and compare it with the user roles specified in the ACF repeater field. If a match is found, it will return the custom price; otherwise, it will return the original product price.

Remember to adjust the field names and values in the code to match your ACF field group settings.

With these steps, you should now have custom prices applied to products based on the user role using ACF in WooCommerce.

Share This On :

Leave a Comment

Your email address will not be published. Required fields are marked *