gpt4 book ai didi

wordpress - 添加自定义字段作为订单上的项目元数据

转载 作者:行者123 更新时间:2023-12-02 11:27:24 25 4
gpt4 key购买 nike

我已向 woocommerce 产品添加了一个自定义字段,它与以下代码配合良好。但我的问题是如何将其添加到 cart_item_data

// Display Text in Admin Panel 
add_action('woocommerce_product_options_general_product_data', 'product_custom_text_field');

function product_custom_text_field()
{

// Custom Product Text Field ( para Tex Area -> woocommerce_wp_textarea_input )

woocommerce_wp_text_input(
array(
'id' => '_optional_text_field',
'label' => __('Customize title', 'woocommerce'),
'placeholder' => '',
'desc_tip' => 'true',
'description' => __('Customizable title for the field that the user must fill out.', 'woocommerce')
)
);
}

保存字段

add_action('woocommerce_process_product_meta', 'product_custom_text_field_save');

function product_custom_text_field_save($post_id)
{
if (!empty($_POST['_optional_text_field'])) {
update_post_meta($post_id, '_optional_text_field', esc_attr($_POST['_optional_text_field']));
}
}

Display The Text in Product Page

add_action('woocommerce_single_variation', 'display_text_field');

function display_text_field()
{
global $post;
if (get_post_meta($post->ID, '_optional_text_field', true)) {
echo "<div class='titulo-c'><label>";
echo get_post_meta($post->ID, '_optional_text_field', true);
echo "</label></div>";
return;
}

echo __('FREE LOCAL SHIPPING', 'woocommerce');
}

到目前为止它工作没有问题,现在我想使用以下代码将其添加到 cart_item_data 中,但它对我不起作用。

add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 25, 2 );
function add_cart_item_data( $cart_item_meta, $product_id ) {

$custom_data = array() ;

$custom_data[ "_optional_text_field"] = isset( $_POST['_optional_text_field'] ) ? sanitize_text_field ( $_POST['_optional_text_field'] ) : "" ;

$cart_item_meta ['custom_data'] = $custom_data ;


return $cart_item_meta;
}

在购物车和结帐页面上显示自定义数据。

add_filter( 'woocommerce_get_item_data', 'get_item_data' , 25, 2 );
function get_item_data ( $other_data, $cart_item ) {
if ( isset( $cart_item [ 'custom_data' ] ) ) {
$custom_data = $cart_item [ 'custom_data' ];

$other_data[] = array( 'name' => 'Title',
'display' => $custom_data['_optional_text_field'] );

}

return $other_data;
}

结果,它只在我看来:标题:________

如果有任何建议让我的代码正常工作,我将不胜感激。

最佳答案

对您的代码进行以下更改,如下所示,这应该有效。

/**
* Add data to cart item
*/
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 25, 2 );
function add_cart_item_data( $cart_item_meta, $product_id ) {


global $woocommerce;
$mytitle_form_data = get_post_meta($product_id, '_optional_text_field', true);

$custom_data = array() ;

$custom_data[ "_optional_text_field"] = $mytitle_form_data;

$cart_item_meta ['custom_data'] = $custom_data ;

return $cart_item_meta;
}

关于wordpress - 添加自定义字段作为订单上的项目元数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56659792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com