我在 woocommerce(最新版本)中的自定义字段有问题。我需要你的帮助。
我的代码
function completed_order($order_id) {
$order = wc_get_order( $order_id );
$customer_id = $order->get_customer_id();
$user = get_user_by('id', $customer_id);
foreach ( $order->get_items() as $item_id => $item ) {
$validity = $item->get_meta( 'validity_field' );
if($validity) {
$a = get_post_meta($item->get_id(), 'validity_field', true);
}
}
}
add_action('woocommerce_order_status_completed', 'completed_order', 10, 1);
function create_custom_field() {
$args = array(
'id' => 'validity_field',
'label' => __( 'Ważność konta', 'waznosc' ),
'class' => 'waznosc-custom-field',
'desc_tip' => true,
'description' => __( 'Wprowadz ilosc dni waznosci konta', 'waznosc' ),
);
woocommerce_wp_text_input( $args );
}
add_action( 'woocommerce_product_options_general_product_data', 'create_custom_field' );
function save_custom_field( $post_id ) {
$product = wc_get_product( $post_id );
$title = isset( $_POST['validity_field'] ) ? $_POST['validity_field'] : '';
$product->update_meta_data( 'validity_field', sanitize_text_field( $title ) );
$product->save();
}
add_action( 'woocommerce_process_product_meta', 'save_custom_field' );
function add_custom_data_to_order( $item, $cart_item_key, $values, $order ) {
foreach( $item as $cart_item_key=>$values ) {
if( isset( $values['title_field'] ) ) {
$item->add_meta_data( __( 'Waznosc konta', 'waznosc' ), $values['validity_field'], true );
}
}
}
add_action( 'woocommerce_checkout_create_order_line_item', 'add_custom_data_to_order', 10, 4 );
现在我在从自定义字段获取数据时遇到问题validity_field。字段被保存到数据库,因为当我编辑产品时值在字段中,但在完成订单后我无法将其挂钩:(我尝试使用 get_post_meta、get_meta 和其他方法,但没有任何作用。有人知道原因吗?
慕标琳琳