Skip to content
Advertisement

add a custom field on a specific product IDs woocommerce

I want to add a custom field “Product Description” on a specific set woocommerce products in functions.php. See below code:

add_action('woocommerce_before_add_to_cart_button','wdm_add_custom_fields');

function wdm_add_custom_fields( $cart ) {

    global $product;

    ob_start();

    ?>
        <div class="wdm-custom-fields">
            <label>Product Description</label>: <input type="text" name="wdm_name">
        </div>
        <div class="clear"></div>

    <?php

    $content = ob_get_contents();
    $targeted_ids = array(29, 27, 28, 72, 84, 95);
    ob_end_flush();
    
    foreach ( $cart->get_cart() as $item ) {
        if ( array_intersect($targeted_ids, array($item['product_id'], $item['variation_id']) ) );
    }

    return $content;
}

I don’t know what went wrong with the code as WordPress gives “There has been a critical error on this website.” Notice. I turned on WordPress Error Reporting in wp-config.php file but it didn’t display any errors.

define('WP_DEBUG', true);
define('WP_DEBUG_DISPLAY', true);

Perhaps the if statement isn’t working. Please advise.

Advertisement

Answer

I have turned debug mode on and got an error in debug log. You have to add define( 'WP_DEBUG_LOG', true ); to the wp-config.php file to log the errors into a file called debug.log

Instead of using $cart in foreach, use WC()->cart->get_cart().

But if your requirement is to display a custom field in the single product page for particular product ID, then you could use the following.

add_action('woocommerce_before_add_to_cart_button','wdm_add_custom_fields');
function wdm_add_custom_fields() {
    global $product;
    $targeted_ids = array(29, 27, 28, 72, 84, 95);
    if(in_array( $product->get_id(), $targeted_ids ) ){
        ?>
            <div class="wdm-custom-fields">
                <label>Product Description</label>: <input type="text" name="wdm_name">
            </div>
            <div class="clear"></div>
        <?php
    }
}

Assuming you need to display custom field on single product page based on product ID, you was wrong. You was trying to get products from the cart, which means, the product should be added to cart inorder to show the custom field. Instead you should access the product ID from global $product variable.

Also you don’t need to return data to an action hook, you could write html or just echo the contents stored in a variable.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement