如何仅在 WooCommerce 购物车页面中显示特定产品的复选框

问题描述 投票:0回答:1

我是 WooCommerce 开发的新手,我正在尝试弄清楚如何仅在将特定产品添加到购物车时才在某些文本旁边显示复选框。

这是我始终显示该文本的代码:

// 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>';
 
}

那么,如何仅当特定产品位于购物车时才显示该复选框?

php wordpress woocommerce hook-woocommerce cart
1个回答
0
投票

如果购物车中有任何定义的产品,您需要检查购物车商品的产品 ID,以显示复选框免责声明(在代码中定义目标产品 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>';
    }
}

代码位于子主题的functions.php 文件中(或插件中)。应该可以。


添加

对于多个定义的产品也是如此:

// 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>';
    }
}

代码位于子主题的functions.php文件中(或插件中)。

© www.soinside.com 2019 - 2024. All rights reserved.