我为每个产品都有一个自定义字段值 . 使用以下代码插入此自定义字段:
<?php
// 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_action( '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_data, $cart_item ) {
$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", "woocommerce" ), "value" => $cart_item['days_manufacture'] );
}
return $custom_items;
} ?>
这段代码完美无缺 .
现在,我想在购物车和结帐时(优惠券通知前)页面显示自定义消息的此自定义字段(days_manufacture)的最高值,此时多个商品位于购物车中,如此屏幕截图中所示 .
我怎样才能做到这一点?
谢谢 .
2 回答
将变量存储在
$_SESSION
中,然后循环遍历它们并选择最高的变量,以便稍后在代码中的任何位置使用它这是一个自定义功能,它将在购物车和结帐时显示消息(在优惠券通知之前)具有最高制造天数的页面...
这是代码:
此代码位于活动子主题(或主题)的function.php文件中,或者也可以放在任何插件文件中 .
此代码经过测试并可以使用 .