在WooCommerce中的购物车中显示自定义字段值

时间:2016-05-21 12:30:18

标签: php wordpress woocommerce

我和我的商店一起使用Wordpress和WooCommerce 我想在购物车和电子邮件订单确认中输出自定义字段的值。

我在functions.php中创建了一个自定义字段:

// Display Fields
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );

// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );

function woo_add_custom_general_fields() {

  global $woocommerce, $post;

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

// Input
woocommerce_wp_text_input( 
    array( 
        'id'                => '_gram', 
        'label'             => __( 'somelabel', 'woocommerce' ), 
        'placeholder'       => '', 
        'description'       => __( 'sometext', 'woocommerce' ),
        'type'              => 'number', 
        'custom_attributes' => array(
                'step'  => 'any',
                'min'   => '0'
            ) 
    )
);

  echo '</div>';

}

function woo_add_custom_general_fields_save( $post_id ){
    // Number Field
    $woocommerce_number_field = $_POST['_gram'];
    if( !empty( $woocommerce_number_field ) )
        update_post_meta( $post_id, '_gram', esc_attr( $woocommerce_number_field ) );

}

在我正在使用的页面上:

get_post_meta( get_the_ID(), '_gram', true );

显示价值和工作完美。

现在,我想在购物车和电子邮件确认中的产品名称下显示相同的值。 但我无法弄清楚如何做到这一点。

有谁知道怎么做?

1 个答案:

答案 0 :(得分:1)

嗯,这是一个漫长的过程,你必须实现两个过滤器&amp;一个行动来实现这一目标。

此外,还有一个plugin用于此目的以及与woocommerce自定义字段相关的许多其他选项。

以下是您问题的直接解决方案。

/**
 * Here we are trying to add your custom data as Cart Line Item
 * SO that we can add this custom data on your cart, checkout, order and email later
 */
function save_custom_data( $cart_item_data, $product_id ) {
    $custom_data = get_post_meta( $product_id, '_gram', true );
    if( $custom_data != null && $custom_data != ""  ) {
        $cart_item_data["gram"] = $custom_data;
    }
    return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'save_custom_data', 10, 2 );

/**
 * Here we are trying to display that custom data on Cart Table & Checkout Order Review Table 
 */
function render_custom_data_on_cart_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["gram"] ) ) {
        $custom_items[] = array( "name" => "Gram", "value" => $cart_item["gram"] );
    }
    return $custom_items;
}
add_filter( 'woocommerce_get_item_data', 'render_custom_data_on_cart_checkout', 10, 2 );

/**
 * We are adding that custom data ( gram ) as Order Item Meta, 
 * which will be carried over to EMail as well 
 */
function save_custom_order_meta( $item_id, $values, $cart_item_key ) {
    if( isset( $values["gram"] ) ) {
        wc_add_order_item_meta( $item_id, "Gram", $values["gram"] );
    }
}
add_action( 'woocommerce_add_order_item_meta', 'save_custom_order_meta', 10, 3 );