phpwordpresswoocommercehook-woocommercecart

Display a checkbox only for specific Product in WooCommerce Cart Page


I'm new to WooCommerce development and I am trying to figure out how to display a checkbox alongside some text only if a specific product is added to the cart.

Here is the code that I have that always display that text:

// Woocommerce - CHECKBOX Disclaimer on Add To Cart Page
add_action('woocommerce_proceed_to_checkout', 'Disclaimer1_test', 10);

function Disclaimer1_test() {

        global $product;
            // How can I check against specific product ID?
            echo '<input type="checkbox" required />';
            echo '<p>This is a test</p>';
 
}

So, how can I display that checkbox only when a specific Product is in Cart?


Solution

  • You need to check in cart items product IDs if any defined product is in cart, to display the checkbox disclaimer (defining in the code the targeted product ID):

    // Display a disclaimer checkbox on Cart Page, if specific product is in cart
    add_action('woocommerce_proceed_to_checkout', 'cart_disclaimer1_test', 10);
    function cart_disclaimer1_test() {
        // Here, define the targeted product ID
        $targeted_product_id = 121;
    
        // Check if the targeted product is in cart
        if ( in_array( $targeted_product_id, array_column( WC()->cart->get_cart(), 'product_id' ) ) ) {
            echo '<input type="checkbox" name="disclaimer1" required />';
            echo '<p>This is a test</p>';
        }
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). It should work.


    Addition

    The same thing for multiple defined products:

    // Display a disclaimer checkbox on Cart Page, if any of the defined products is in cart
    add_action('woocommerce_proceed_to_checkout', 'cart_disclaimer1_test', 10);
    function cart_disclaimer1_test() {
        // Here, define the targeted product IDs
        $targeted_product_ids = array(121, 136);
    
        // Check if any of the targeted products is in cart
        if ( array_intersect( $targeted_product_ids, array_column( WC()->cart->get_cart(), 'product_id' ) ) ) {
            echo '<input type="checkbox" name="disclaimer1" required />';
            echo '<p>This is a test</p>';
        }
    }
    

    Code goes in functions.php file of your child theme (or in a plugin).