How to Password Protect Add to Cart button in WooCommerce

Once a WooCommerce product page is password protected with our PPWP Pro plugin, the whole page will be hidden under a password form by default.

If you want to hide the Add to Cart button only, simply add the following code snippet to your (child) theme’s functions.php file.

/**
* Hide Add to Cart on all password protected pages.
*/

function ppwp_replace_add_to_card()
{
    echo get_the_password_form();
}
add_filter(
    'post_password_required',
    function ($required, $post) {
        global $post;
        if (!$post->ID) {
            return $required;
        }

        if (!function_exists('is_product')) {
            return $required;
        }

        if ($required && is_product()) {
            add_filter('woocommerce_is_purchasable', '__return_false');
            add_action('woocommerce_simple_add_to_cart', 'ppwp_replace_add_to_card');
            add_action('woocommerce_grouped_add_to_cart', 'ppwp_replace_add_to_card');

            return false;
        }

        return $required;
    },
    200,
    2
);

Your WooCommerce product page will display as below:

Hide Add to Cart button on certain pages only

Use the following code snippet if you want to hide this button on specific password protected WooCommerce product pages only.

/** 
 * Hide Add to Cart on certain pages only (e.g. post_id=91) 
 */

function ppwp_replace_add_to_card()
{
    echo get_the_password_form();
}
add_filter(
    'post_password_required',
    function ($required, $post) {
        global $post;
        if (!$post->ID) {
            return $required;
        }

        if (!function_exists('is_product')) {
            return $required;
        }

        $posts_included = [91];
        if (!in_array($post->ID, $posts_included)) {
            return $required;
        }

        if ($required && is_product()) {
            add_filter('woocommerce_is_purchasable', '__return_false');
            add_action('woocommerce_simple_add_to_cart', 'ppwp_replace_add_to_card');
            add_action('woocommerce_grouped_add_to_cart', 'ppwp_replace_add_to_card');

            return false;
        }

        return $required;
    },
    200,
    2
);

Get the post ID by hovering over the desired post title.

Lasted updated on February 17, 2021