Admin product pages custom field displayed in Cart and checkout

后端 未结 1 900
挽巷
挽巷 2020-12-07 02:47

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 fiel

相关标签:
1条回答
  • 2020-12-07 03:19

    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

    0 讨论(0)
提交回复
热议问题