Ответ 1
Здесь мы используем другой подход, чем настраиваемые поля, созданные с помощью ACF-плагина. Мы создаем выделенный метабокс с двумя полями внутри него, расположенными в правой колонке на страницах бэкэнда, с помощью этого кода:
//
//Adding Meta container admin product pages
//
add_action( 'add_meta_boxes', 'cc_add_meta_boxes' );
if ( ! function_exists( 'cc_add_meta_boxes' ) )
{
function cc_add_meta_boxes()
{
global $woocommerce, $post;
add_meta_box( 'cc_other_fields', __('Sessions','woocommerce'), 'cc_add_other_fields_for_packaging', 'product', 'side', 'core' );
}
}
//
//adding Meta field in the meta container admin product pages
//
if ( ! function_exists( 'cc_save_wc_order_other_fields' ) )
{
function cc_add_other_fields_for_packaging()
{
global $woocommerce, $product, $post;
$meta_field_session_period = get_post_meta( $post->ID, '_session_period', true ) ? get_post_meta( $post->ID, '_session_period', true ) : '';
$meta_field_number_sessions = get_post_meta( $post->ID, '_number_sessions', true ) ? get_post_meta( $post->ID, '_number_sessions', true ) : '';
echo '<input type="hidden" name="cc_other_meta_field_nonce" value="' . wp_create_nonce() . '">
<p><label style="display:inline-block;" class="cc_opt_label">' . __( "Session period", "your_theme_slug" ) . '</label><br>
<input type="text" style="width:250px;";" name="session_period" placeholder="' . $meta_field_session_period . '" value="' . $meta_field_session_period . '"></p>
<p><label style="display:inline-block;" class="cc_opt_label">' . __( "Number of sessions", "your_theme_slug" ) . '</label><br>
<input type="text" style="width:250px;";" name="number_sessions" placeholder="' . $meta_field_number_sessions . '" value="' . $meta_field_number_sessions . '"><br></p>';
}
}
//Save the data of the product Meta fields pages
add_action( 'save_post', 'cc_save_product_other_fields', 10, 1 );
if ( ! function_exists( 'cc_save_product_other_fields' ) )
{
function cc_save_product_other_fields( $post_id ) {
// We need to verify this with the proper authorization (security stuff).
// Check if our nonce is set.
if ( ! isset( $_POST[ 'cc_other_meta_field_nonce' ] ) ) {
return $post_id;
}
$nonce = $_REQUEST[ 'cc_other_meta_field_nonce' ];
//Verify that the nonce is valid.
if ( ! wp_verify_nonce( $nonce ) ) {
return $post_id;
}
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return $post_id;
}
// Check the user permissions.
if ( 'page' == $_POST[ 'post_type' ] ) {
if ( ! current_user_can( 'edit_page', $post_id ) ) {
return $post_id;
}
} else {
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return $post_id;
}
}
// --- Its safe for us to save the data ! --- //
// Sanitize user input and update the meta field in the database.
update_post_meta( $post_id, '_session_period', $_POST[ 'session_period' ] );
update_post_meta( $post_id, '_number_sessions', $_POST[ 'number_sessions' ] );
}
}
Примечание. вы вставляете этот код в файл function.php
активной дочерней темы или темы.
КАК ИСПОЛЬЗОВАТЬ ЭТО В ВАШЕМ ШАБЛОНЕ КОДА + ИСПРАВЛЕННЫЕ ОШИБКИ:
Вам не нужно использовать ACF-плагин для этих простых полей. Вы также найдете недостающий код для получения идентификатора заказа, идентификатора продукта и отображения в моей учетной записи > таблицы недавних заказов, данных сеансов:
// This is your existing code:
<?php
<?php foreach ( $customer_orders as $customer_order ) :
$order = wc_get_order( $customer_order );
// This way you can retrieve order ID:
$order_id = $order->post->ID;
Что вам нужно для:
if (get_field('date_ended', $order_id) ) :
// or
if (get_field('date_ended', $order->post->id) ) :
// instead of:
//get_field('date_ended', $order->id)
// and use </p> instead of <p> at the end of this line:
<p class="sendungsnummer"><?php the_field('date_ended', $order->id); ?></p>
.../...
foreach($order->get_items() as $item) {
$product_name = $item['name'];
// This way you can retrieve product ID:
$product_id = $item['product_id'];
.../...
Вы получите доступ к этим данным с идентификатором продукта (или идентификатором сообщения) и функцией Wordpress get_post_meta()
в шаблоне:
// Then you get your data fields with this two:
$session_period = get_post_meta( $product_id, '_session_period', true );
$number_sessions = get_post_meta( $product_id, '_number_sessions', true );
И вы будете использовать их, отображая их значения таким образом:
echo $session_period; // For Session period
echo $number_sessions; // For Number of sessions
.../...
elseif ( 'sessions' === $column_id ) // <=== It is 'sessions' instead of 'session' !!!
Этот подход более профессиональный и более чистый:
Это основано на другой проблеме, но какой-то подобный:
WooCommerce: добавьте пользовательскую Metabox на страницу заказа администратора