Search code examples
wordpresswoocommercehook-woocommerce

Woocommerce adding custom text to checkout page by specific product


First of all, I am learning a lot day by day on here, thank you. I hope some of you can help with this.

I want to add a custom text to the WooCommerce Checkout page. But I want this text to appear only in a specific product. For example, I want to add a custom text/date when a product with a product ID of 348. I tried to add it with the code below, but I could not reach a result. Where is the place I missed and didn't see? I would be glad if you help.

add_action( 'woocommerce_review_order_before_payment', 'my_custom_checkout_field' );

function my_custom_checkout_field( $checkout ) {

$dayAfterMonth = strtotime('+1 month');


    if(is_product() && get_the_id() == 348) {
        echo "Today is " . date("d/m/Y", $dayAfterMonth) . "<br>";
    }
    else {
        echo '<div id="my_custom_checkout_field"><h3>' . __('About Free Trial') . '</h3>';
    }
}

Solution

  • Try this

    add_action( 'woocommerce_review_order_before_payment', 'my_custom_checkout_field' );
    
    function my_custom_checkout_field( $checkout ) {
    
    $dayAfterMonth = strtotime('+1 month');
    
    $items = WC()->cart->get_cart();
    
    foreach ($items as $item => $values)
        {
            $_product = $values['data']->post;
            if($_product->ID == 348) {
            echo "Today is " . date("d/m/Y", $dayAfterMonth) . "<br>";
        }
        else {
            echo '<div id="my_custom_checkout_field"><h3>' . __('About Free Trial') . '</h3>';
        }
        }
    
        
    }