How to set prices per user in WooCommerce without plugins and using code?

Welcome, WordPress and WooCommerce enthusiasts. As a web programmer specialized in these platforms and a lover of sharing knowledge, today I bring you a tutorial on how to set prices per user in WooCommerce programmatically. This guide will be useful if you wish to offer customized prices to your customers based on their user roles or specific characteristics. Let's get started!

woman coding on computer
Photo by ThisIsEngineering on Pexels.com

Step 1: Create a custom plugin

To keep our code clean and organized, we are going to create a custom plugin. In the directory wp-content/plugins of your WordPress installation, create a new folder named woocommerce-custom-prices. Inside this folder, create a PHP file named woocommerce-custom-prices.php and add the following code:

<?php

Step 2: Create a function to set custom prices

Next, add a function in the file woocommerce-custom-prices.php that handles the logic for setting custom prices per user. In this example, we will offer a 10% discount to users with the “subscriber” role.

function set_custom_prices($price, $product) {
    // Obtener el usuario actual
    $current_user = wp_get_current_user();

    // Verificar si el usuario es un suscriptor
    if (in_array('subscriber', $current_user->roles)) {
        // Aplicar un descuento del 10%
        $price = $price * 0.9;
    }

    return $price;
}

Step 3: Hook the function to the appropriate filter

To apply our function to product prices in WooCommerce, we will use the filter woocommerce_product_get_price. Add the following code below the function set_custom_prices:

add_filter('woocommerce_product_get_price', 'set_custom_prices', 10, 2);

Complete Code

<?php;

Step 4: Activate the plugin

Finally, activate the plugin from the plugins administration page in your WordPress dashboard. Now, users with the “subscriber” role should receive a 10% discount on all products in your WooCommerce store.

This is just a simple example of how to set custom prices per user in WooCommerce. You can adapt the function set_custom_prices to adjust prices according to different user roles or specific characteristics of your customers.

Improving the functionality: Custom prices based on user metadata

Now that we know how to set custom prices by user role, we are going to improve our functionality to make it more flexible. Instead of basing the discount on the user role, we will allow administrators to set a specific discount for each user via a custom field in their profile.

Step 1: Add a custom field on the user profile page

To add a custom field on the user profile page, we will use the action show_user_profile y edit_user_profile. Add the following code in the file woocommerce-custom-prices.php:

function add_custom_user_discount_field($user) {
    $discount = get_user_meta($user-&gt;ID, 'custom_user_discount', true);
    ?&gt;
    <h3>Personalized discount in WooCommerce</h3>
    <table class="form-table">
        <tr>
            <th><label for="custom_user_discount">Discount (%)</label></th>
            <td>
                <input type="number" name="custom_user_discount" id="custom_user_discount" value="<?php echo esc_attr($discount); ?>" class="regular-text" /><br />
                <span class="description">Enter the discount percentage for this user (0-100).</span>
            </td>
        </tr>
    </table>
    &lt;?php;

Step 2: Save the custom field value

To save the custom field value when the user profile is updated, we will use the action personal_options_update y edit_user_profile_update. Add the following code in the file woocommerce-custom-prices.php:

function save_custom_user_discount_field($user_id) {
    if (!current_user_can('edit_user', $user_id)) {
        return false;
    }

    $discount = isset($_POST['custom_user_discount']) ? intval($_POST['custom_user_discount']) : 0;
    update_user_meta($user_id, 'custom_user_discount', $discount);
}

add_action('personal_options_update', 'save_custom_user_discount_field');
add_action('edit_user_profile_update', 'save_custom_user_discount_field');

Step 3: Modify the custom prices function

We are going to modify our function set_custom_prices to apply the discount based on the custom field value instead of the user role.

function set_custom_prices($price, $product) {
    // Obtener el usuario actual
    $current_user = wp_get_current_user();

    // Obtener el descuento personalizado del usuario
    $discount = get_user_meta($current_user->ID, 'custom_user_discount', true);

    if (!empty($discount) && is_numeric($discount) && $discount > 0) {
        // Calcular el precio con descuento
        $price = $price * (1 - $discount / 100);
    }

    return $price;
}

With these changes, administrators will now be able to set a specific discount percentage for each user from the user profile page. The discount will be automatically applied to all products in the WooCommerce store for that user.

Step 4: Display the applied discount on the product page (optional)

To improve the user experience, we can display the applied discount on the product page. To do this, we will use the action woocommerce_single_product_summary. Add the following code in the file woocommerce-custom-prices.php:

function display_user_discount() {
    global $product;

    // Obtener el usuario actual
    $current_user = wp_get_current_user();

    // Obtener el descuento personalizado del usuario
    $discount = get_user_meta($current_user-&gt;ID, 'custom_user_discount', true);

    if (!empty($discount) &amp;&amp; is_numeric($discount) &amp;&amp; $discount &gt; 0) {
        echo '<div class="woocommerce-user-discount">';'<p><strong>Discount applied:</strong> ' . $discount . '%</p>';'</div>';

This code displays the applied discount percentage on the product page for the current user, right after the product price.

Conclusion

With these steps, we have created a more advanced and flexible solution for setting custom prices per user in WooCommerce. Administrators can now apply specific discounts to each user, and users can see their discounts applied on the product page.

This tutorial is just the beginning of the possibilities offered by WooCommerce customization. You can continue experimenting and adapting these functions to the specific needs of your online store.

Do you need help with a web project?

Do you need help with a web project? Don't hesitate to contact me. I develop complete and customized solutions with WordPress and PHP, using modern tools and processes, HTML, CSS, SCSS, PHP, JavaScript, Bootstrap, and more. Ready? Send me a message and let's talk about your web project!