Viewed   93 times

I have created a Custom Field in WooCommerce Admin on the general settings tab of product pages, to insert a some days for manufacture. I would like to show this custom field value on cart and checkout pages above the name of each product.

Here is my code:

// Insert a Custom Admin Field
function woo_add_custom_general_fields() {

    echo '<div class="options_group">';

    woocommerce_wp_text_input( array( 
        'id'                => 'days_manufacture', 
        'label'             => __( 'Days for Manufacture', 'woocommerce' ), 
        'placeholder'       => '', 
        'description'       => __( 'Insert here', 'woocommerce' ),
        'type'              => 'number', 
        'custom_attributes' => 
        array(
            'step'  => 'any',
            'min'   => '1'
        ) 
    ) );
    echo '</div>';
}
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );


// Save field
function woo_add_custom_general_fields_save( $post_id ){
    $woocommerce_number_field = $_POST['days_manufacture'];
    if( !empty( $woocommerce_number_field ) )
        update_post_meta( $post_id, 'days_manufacture', esc_attr( $woocommerce_number_field ) );
}
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );


function save_days_field( $cart_item_data, $product_id ) {
    if( isset( $_REQUEST['days_manufacture'] ) ) {
        $cart_item_data[ 'days_manufacture' ] = get_post_meta( $post->ID, 'days_manufacture',true );

/* below statement make sure every add to cart action as unique line item */

   $cart_item_data['unique_key'] = md5( microtime().rand() );
    }
    return $cart_item_data;
}
add_action( 'woocommerce_add_cart_item_data', 'save_days_field', 10, 2 );


function render_meta_on_cart_and_checkout( $cart_data, $cart_item = null ) {
    $custom_items = array();
    /* Woo 2.4.2 updates */
    if( !empty( $cart_data ) ) {
        $custom_items = $cart_data;
    }
    if( isset( $cart_item['days_manufacture'] ) ) {
        $custom_items[] = array( "name" => 'Days:', "value" => $cart_item['days_manufacture'] );
    }
    return $custom_items;
}
add_filter( 'woocommerce_get_item_data', 'render_meta_on_cart_and_checkout', 10, 2 );

But this is not working as I can't display the custom field value on cart and checkout pages.

How can I achieve this?

Thanks

 Answers

4

I have tested your code and corrected some portions to make that product custom field appear on cart and checkout pages.

Here is that corrected code:

// Insert a Custom Admin Field
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
function woo_add_custom_general_fields() {
    echo '<div class="options_group">';

    woocommerce_wp_text_input( array(
        'id'                => 'days_manufacture',
        'label'             => __( 'Days for Manufacture', 'woocommerce' ),
        'placeholder'       => '',
        'description'       => __( 'Insert here', 'woocommerce' ),
        'type'              => 'number',
        'custom_attributes' => array(
            'step'  => 'any',
            'min'   => '1'
        ),
    ) );

    echo '</div>';
}

// Save the field
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
function woo_add_custom_general_fields_save( $post_id ){
$woocommerce_number_field = $_POST['days_manufacture'];
if( !empty( $woocommerce_number_field ) )
    update_post_meta( $post_id, 'days_manufacture', esc_attr( $woocommerce_number_field ) );
}

// Store custom field
add_filter( 'woocommerce_add_cart_item_data', 'save_days_field', 10, 2 );
function save_days_field( $cart_item_data, $product_id ) {
    $special_item = get_post_meta( $product_id , 'days_manufacture',true );
    if(!empty($special_item)) {
        $cart_item_data[ 'days_manufacture' ] = $special_item;

        // below statement make sure every add to cart action as unique line item
        $cart_item_data['unique_key'] = md5( microtime().rand() );
        WC()->session->set( 'days_manufacture', $special_item );
    }
    return $cart_item_data;
}


// Render meta on cart and checkout
add_filter( 'woocommerce_get_item_data', 'rendering_meta_field_on_cart_and_checkout', 10, 2 );

function rendering_meta_field_on_cart_and_checkout( $cart_item_data, $cart_item ) {
    if( isset( $cart_item['days_manufacture'] ) ) {
        $cart_item_data[] = array( "name" => __( "Days", "woocommerce" ), "value" => $cart_item['days_manufacture'] );
    }
    return $cart_item_data;
}

Naturally, this goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.

Reference: WooCommerce : Add custom Metabox to admin order page

Saturday, October 15, 2022
5

In your last hooked function you have a missing argument, which is a similar to $loop argument in your 3rd function. So I have made little changes in your code:

// Add product Barcode custom field
add_action('woocommerce_product_options_sku','add_barcode_custom_field' );
function add_barcode_custom_field(){
    woocommerce_wp_text_input( array(
        'id'          => '_barcode',
        'label'       => __('Barcode','woocommerce'),
        'placeholder' => 'Scan Barcode',
        'desc_tip'    => 'true',
        'description' => __('This is the Scan barcode field for this product.','woocommerce')
    ) ); 
}

// Save product Barcode custom field
add_action( 'woocommerce_process_product_meta', 'save_barcode_custom_field', 10, 1 );
function save_barcode_custom_field( $post_id ){
    if( isset($_POST['_barcode']) )
        update_post_meta( $post_id, '_barcode', esc_attr( $_POST['_barcode'] ) );
}

// Add Variation Barcode custom field
add_action( 'woocommerce_variation_options_pricing', 'add_barcode_variation_custom_field', 10, 3 );
function add_barcode_variation_custom_field( $loop, $variation_data, $variation ){

    $variation_barcode = get_post_meta($variation->ID,"_barcode", true );
    if( ! $variation_barcode ) $variation_barcode = "";

    woocommerce_wp_text_input( array(
        'id'          => '_barcode['.$loop.']',
        'label'       => __('Variation Barcode','woocommerce'),
        'placeholder' => 'Scan Barcode',
        'desc_tip'    => 'true',
        'description' => __('This is the Scan barcode field for this variation.','woocommerce')
        'value'       => get_post_meta($variation->ID,"_barcode", true ),
    ) );
}

// Save Variation Barcode custom field value
add_action( 'woocommerce_save_product_variation', 'save_barcode_variation_custom_field', 10, 2 );
function save_barcode_variation_custom_field( $variation_id, $i ){
    if( isset($_POST['_barcode'][$i]) )
        update_post_meta( $variation_id, '_barcode', sanitize_text_field($_POST['_barcode'][$i]) );
}

This code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works for WooCommerce version 2.6+ and 3.0+

Wednesday, August 17, 2022
 
3

Your save function should be like

function woo_add_custom_general_fields_save( $post_id ){

// Customer text ISBN Field
$woocommerce_text_field = $_POST['_ISBN_field'];
if( !empty( $woocommerce_text_field ) )
    update_post_meta( $post_id, '_ISBN_field', esc_attr( $woocommerce_text_field ) );
else
    update_post_meta( $post_id, '_ISBN_field', '' );
}

If !empty( $woocommerce_text_field ) returns true only if $_POST['_ISBN_field'] has some value so the post meta is not updated if $_POST['_ISBN_field'] is empty

Friday, August 26, 2022
 
zeekay
 
5

UPDATE (A WORKIG SOLUTION TO SAVE AND RETRIEVE YOUR LABELS NAMES)

I Have make some changes In your code adding hidden imput fields with your label names. When saving/submitting the data, it will save also automatically the label names.

Here is the complete code:

// ADDING A TAB TO WOOCOMMERCE PRODUCT DATA METABOX
add_filter( 'woocommerce_product_data_tabs', 'launch_product_tab_content_tab' , 99 , 1 );
function launch_product_tab_content_tab( $product_data_tabs ) {
    $product_data_tabs['launch'] = array(
        'label' => __( 'Launch', 'my_text_domain' ),
        'target' => 'launch_contents',
    );
    return $product_data_tabs;
}

// ADDING A FIELDS INSIDE THE TAB IN WOOCOMMERCE PRODUCT DATA METABOX
add_action( 'woocommerce_product_data_panels', 'launch_product_tab_content' );
function launch_product_tab_content() {
    global $woocommerce, $post;

    // Setting here your labels
    $label_text_announced       = __( 'Announced(Global)', 'woocommerce' );
    $label_text_announced_ph    = __( 'Announced(Philippines)', 'woocommerce' );
    $label_text_availability_ph = __( 'Availability(Philippines)', 'woocommerce' );

    ?>
    <div id='launch_contents' class='panel woocommerce_options_panel'>
        <div class='options_group'>
    <?php

        woocommerce_wp_text_input( array(
            'id'            => '_text_announced',
            'label'         => $label_text_announced,
            'desc_tip'      => 'true',
            'description'   => __( 'Year and Month it was announced global', 'woocommerce' ),
            'type'          => 'text',
        ) );

        woocommerce_wp_text_input( array(
            'id'            => '_text_announced_ph',
            'label'         => $label_text_announced_ph,
            'desc_tip'      => 'true',
            'description'   => __( 'Year and Month it was announced global', 'woocommerce' ),
            'type'          => 'text',
        ) );

        woocommerce_wp_text_input( array(
            'id'            => '_text_availability_ph',
            'label'         => $label_text_availability_ph,
            'desc_tip'      => 'true',
            'description'   => __( 'Schedule date of availability in the Philippines', 'woocommerce' ),
            'type'          => 'text',
        ) );

        // Addind hidden imputs fields for your labels
        echo '<input type="hidden" id="text_announced_label" name="text_announced_label" value="'.$label_text_announced.'" />
        <input type="hidden" id="text_announced_ph_label" name="text_announced_ph_label" value="'.$label_text_announced_ph.'" />
        <input type="hidden" id="text_availability_ph_label" name="text_availability_ph_label" value="'.$label_text_availability_ph.'" />';

    ?>
        </div>
    </div>
    <?php
}

// SAVING THE FIELDS DATA from THE TAB IN WOOCOMMERCE PRODUCT DATA METABOX
add_action( 'woocommerce_process_product_meta', 'save_launch_product_tab_content' );
function save_launch_product_tab_content( $post_id ){

    // Saving the data with the hidden data labels names

    if(isset($_POST['_text_announced'])){
        update_post_meta( $post_id, '_text_announced', $_POST['_text_announced'] );
        update_post_meta( $post_id, '_text_announced_label', $_POST['text_announced_label'] );
    }

    if(isset($_POST['_text_announced_ph'])){
        update_post_meta( $post_id, '_text_announced_ph', $_POST['_text_announced_ph'] );
        update_post_meta( $post_id, '_text_announced_ph_label', $_POST['text_announced_ph_label'] );
    }

    if(isset($_POST['_text_availability_ph'])){
        update_post_meta( $post_id, '_text_availability_ph', $_POST['_text_availability_ph'] );
        update_post_meta( $post_id, '_text_availability_ph_label', $_POST['text_availability_ph_label'] );
    }

}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Once submitted (SAVED) all the data is set in wp_postmeta table for the current product ID (even the label names), see below what you get in this database table (the ID of the product is 99 here):

So now you can get your label name and the corresponding data value…

Here now a function that will automate that process and set those values in an array:

function get_label_and_value($product_id, $meta_key){
    // As the meta_key of the label have the same slug + '_label' we get it here
    $key_label = $meta_key . '_label';
    
    // Getting the values
    $meta_value = get_post_meta($product_id, $meta_key, true);
    $label_name = get_post_meta($product_id, $key_label, true);

    // Setting this data in an array:
    $result = array('label' => $label_name, 'value' => $meta_value);

    // Returning the data array
    return $result;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Now we can use this function in any PHP file:

<?php
    // The product ID
    $product_id = $product_id;

    // The field key
    $field_key = "_text_announced";

    // Using our function
    $field1 = get_label_and_value($product_id, $field_key);

    // Displaying the data (just as you expected to do)
    echo $field1['label'] . ': ' . $field1['value'];

?>

And you will get:

Announced(Global): April 2016

So no need of ACF here

This code is tested and works...

Thursday, December 22, 2022
 
4

Here is the complete code to Store product custom field in cart object and display that in Cart and Checkout pages:

// Output the Custom field in Product pages
add_action("woocommerce_before_add_to_cart_button", "options_on_single_product", 1);
function options_on_single_product(){
    ?>
        <label for="custom_field">
            <input type="radio" name="custom_field" checked="checked" value="option1"> option 1 <br />
            <input type="radio" name="custom_field" value="option2"> option 2
        </label> <br />
    <?php
}

// Stores the custom field value in Cart object
add_filter( 'woocommerce_add_cart_item_data', 'save_custom_product_field_data', 10, 2 );
function save_custom_product_field_data( $cart_item_data, $product_id ) {
    if( isset( $_REQUEST['custom_field'] ) ) {
        $cart_item_data[ 'custom_field' ] = esc_attr($_REQUEST['custom_field']);
        // below statement make sure every add to cart action as unique line item
        $cart_item_data['unique_key'] = md5( microtime().rand() );
    }
    return $cart_item_data;
}

// Outuput custom Item value in Cart and Checkout pages
add_filter( 'woocommerce_get_item_data', 'output_custom_product_field_data', 10, 2 );
function output_custom_product_field_data( $cart_data, $cart_item ) {
    if( isset( $cart_item['custom_field'] ) ) {
        $cart_data[] = array(
            'key'       => __('Custom Item', 'woocommerce'),
            'value'     => $cart_item['custom_field'],
            'display'   => $cart_item['custom_field'],
        );
    }
    return $cart_data;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.

Friday, December 16, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share