В настоящее время я успешно добавляю поле на свои страницы продуктов WooCommerce, которое показывает значение:
- в корзине (передняя часть),
- на странице проверки (front end),
- на странице заказа (передняя часть),
- и в отдельной странице клиента (задний конец).
Проблема: он не отображается в качестве настраиваемого поля в "настраиваемых полях" администратора "Метабокс" со значением внутри него, а также как текст на странице заказа.
Вот мой рабочий код:
// Add the field to the product
add_action('woocommerce_before_add_to_cart_button', 'my_custom_checkout_field');
function my_custom_checkout_field() {
echo '<div id="my_custom_checkout_field"><h3>'.__('My Field').'</h3>';
echo '<label>fill in this field</label> <input type="text" name="my_field_name">';
echo '</div>';
}
// Store custom field
function save_my_custom_checkout_field( $cart_item_data, $product_id ) {
if( isset( $_REQUEST['my_field_name'] ) ) {
$cart_item_data[ 'my_field_name' ] = $_REQUEST['my_field_name'];
/* below statement make sure every add to cart action as unique line item */
$cart_item_data['unique_key'] = md5( microtime().rand() );
}
return $cart_item_data;
}
add_action( 'woocommerce_add_cart_item_data', 'save_my_custom_checkout_field', 10, 2 );
// Render meta on cart and checkout
function render_meta_on_cart_and_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['my_field_name'] ) ) {
$custom_items[] = array( "name" => 'My Field', "value" => $cart_item['my_field_name'] );
}
return $custom_items;
}
add_filter( 'woocommerce_get_item_data', 'render_meta_on_cart_and_checkout', 10, 2 );
// This is what I think needs changing?
function subscription_order_meta_handler( $item_id, $values, $cart_item_key ) {
if( isset( $values['my_field_name'] ) ) {
wc_add_order_item_meta( $item_id, "My Field", $values['my_field_name'] );
}
}
add_action( 'woocommerce_add_order_item_meta', 'subscription_order_meta_handler', 1, 3 );
Я думаю, что это последний бит кода, который нуждается в изменении. В настоящее время он отображает текст под элементом заказа, поэтому, возможно, мне нужно настроить wc_add_order_item_meta
на что-то еще?
Я пробовал все, но, похоже, не работает. Я могу заставить его работать, когда мое поле находится на странице проверки, но не тогда, когда я вытаскиваю его с страницы продукта.
Возможно, мне не хватает фрагмента процесса проверки?