programing

최근 주문 템플릿 및 관리 주문에 제품 게시 유형 고급 사용자 지정 필드 표시(woocommerce)

codeshow 2023. 3. 28. 22:24
반응형

최근 주문 템플릿 및 관리 주문에 제품 게시 유형 고급 사용자 지정 필드 표시(woocommerce)

최근 WooCommerce 주문 템플릿에서 작성한 필드를 표시하려고 하는데 PHP에 대한 지식이 부족합니다.

sessions라는 필드를 만들어 제품 포스트 타입으로 등록했습니다.사용자가 제품을 구입하면 해당 커스텀 필드의 "세션" 값을 [내 계정]> [최근 주문] (템플릿)에 표시해 주셨으면 합니다.

나는 해답과 해결책을 찾으려고 노력했지만 막힌 것 같다.

여기 주문하신 코드의 커스터마이즈가 있습니다.작업 중인 php 템플릿입니다.며칠째 해킹을 하고 있어서 최근 주문표에 이 값을 표시할 수 없는 것 같습니다.

업데이트 - 문제 해결을 위한 이미지 및 설명 추가

1) 보시는 바와 같이 2종류의 필드를 작성하여 제품 포스트 타입으로 등록했습니다.

여기에 이미지 설명 입력

2) 다음으로 작성한2개의 필드에 값을 설정합니다.

여기에 이미지 설명 입력

3) 사용자 또는 고객이 아이템/제품/패키지를 구입한 경우.이 두 값을 사용자 내 계정 템플릿의 최근 주문에서 "세션" 열 아래에 표시했으면 합니다.

여기에 이미지 설명 입력

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

$my_orders_columns = apply_filters( 'woocommerce_my_account_my_orders_columns', array(
    'order-number'   => __( 'Package', 'woocommerce' ),
    'sessions'       => __( 'Session', 'woocommerce' ),
    'order-total'    => __( 'Package Prize', 'woocommerce' ),
    'order-date'     => __( 'Date', 'woocommerce' ),
    'order-end-date' => __( 'End Date', 'woocommerce'),
    'order-status'   => __( 'Status', 'woocommerce' ),
    'order-actions'  => ' ',
) );

$customer_orders = get_posts( apply_filters( 'woocommerce_my_account_my_orders_query', array(
    'numberposts' => $order_count,
    'meta_key'    => '_customer_user',
    'meta_value'  => get_current_user_id(),
    'post_type'   => wc_get_order_types( 'view-orders' ),
    'post_status' => array_keys( wc_get_order_statuses() )
) ) );

if ( $customer_orders ) : ?>

    <h2><?php // echo apply_filters( 'woocommerce_my_account_my_orders_title', __( 'Recent Orders', 'woocommerce' ) ); ?></h2>

    <table class="shop_table shop_table_responsive my_account_orders">

        <thead>
            <tr>
                <?php foreach ( $my_orders_columns as $column_id => $column_name ) : ?>
                    <th class="<?php echo esc_attr( $column_id ); ?>"><span class="nobr"><?php echo esc_html( $column_name ); ?></span></th>
                <?php endforeach; ?>
            </tr>
        </thead>

        <tbody>
            <?php foreach ( $customer_orders as $customer_order ) :
                $order      = wc_get_order( $customer_order );
                $item_count = $order->get_item_count();
                ?>
                <tr class="order">
                    <?php foreach ( $my_orders_columns as $column_id => $column_name ) : ?>
                        <td class="<?php echo esc_attr( $column_id ); ?>" data-title="<?php echo esc_attr( $column_name ); ?>">
                            <?php if ( has_action( 'woocommerce_my_account_my_orders_column_' . $column_id ) ) : ?>
                                <?php do_action( 'woocommerce_my_account_my_orders_column_' . $column_id, $order ); ?>

                            <?php elseif ( 'order-number' === $column_id ) : ?>
                                <?php foreach($order->get_items() as $item) {
                                    $product_name = $item['name'];

                                } ?>

                                <?php echo $product_name;?>

                            <?php elseif ( 'session'  === $column_id ) : ?>
                                <?php if (get_field('session_period', $product->id) ) :  ?>



                            <?php endif; ?>


                            <?php elseif ( 'order-total' === $column_id ) : ?>
                                <?php echo sprintf( _n( '%s', '%s', $item_count, 'woocommerce' ), $order->get_formatted_order_total(), $item_count ); ?>

                            <?php elseif ( 'order-date' === $column_id ) : ?>
                                <time datetime="<?php echo date( 'Y-m-d', strtotime( $order->order_date ) ); ?>" title="<?php echo esc_attr( strtotime( $order->order_date ) ); ?>"><?php echo date_i18n( get_option( 'date_format' ), strtotime( $order->order_date ) ); ?></time>

                            <?php /* Order End Date */ ?>
                            <?php elseif ( 'order-end-date' === $column_id ) : ?>
                                <?php if (get_field('date_ended', $order->id) ) :    ?>
                                <p class="sendungsnummer"><?php the_field('date_ended', $order->id); ?>

                            <?php endif; ?>

                            <?php elseif ( 'order-status' === $column_id ) : ?>
                                <?php echo wc_get_order_status_name( $order->get_status() ); ?>


                            <?php elseif ( 'order-actions' === $column_id ) : ?>
                                <?php
                                    $actions = array(
                                        'pay'    => array(
                                            'url'  => $order->get_checkout_payment_url(),
                                            'name' => __( 'Pay', 'woocommerce' )
                                        ),
                                        'view'   => array(
                                            'url'  => $order->get_view_order_url(),
                                            'name' => __( 'View', 'woocommerce' )
                                        ),
                                        'cancel' => array(
                                            'url'  => $order->get_cancel_order_url( wc_get_page_permalink( 'myaccount' ) ),
                                            'name' => __( 'Cancel', 'woocommerce' )
                                        )
                                    );

                                    if ( ! $order->needs_payment() ) {
                                        unset( $actions['pay'] );
                                    }

                                    if ( ! in_array( $order->get_status(), apply_filters( 'woocommerce_valid_order_statuses_for_cancel', array( 'pending', 'failed' ), $order ) ) ) {
                                        unset( $actions['cancel'] );
                                    }

                                    /* -------- View Button --------
                                    if ( $actions = apply_filters( 'woocommerce_my_account_my_orders_actions', $actions, $order ) ) {
                                        foreach ( $actions as $key => $action ) {
                                            echo '<a href="' . esc_url( $action['url'] ) . '" class="button ' . sanitize_html_class( $key ) . '">' . esc_html( $action['name'] ) . '</a>';
                                        }
                                    }
                                    */
                                ?>
                            <?php endif; ?>
                        </td>
                    <?php endforeach; ?>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
<?php endif; ?>

여기서는 ACF 플러그인으로 작성된 커스텀필드와는 다른 접근방식을 채택하고 있습니다.백엔드 제품 페이지의 오른쪽 열에 다음 코드를 사용하여 2개의 필드가 포함된 전용 메타박스를 만듭니다.

//
//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's 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 플러그인을 사용할 필요가 없습니다.주문 ID, 제품 ID를 취득하기 위한 코드도 찾을 수 있습니다.또한 [내 계정(My account)]> [ 최근 주문(recent orders)]테이블에 세션 데이터가 표시됩니다.

// 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'];

... / ...

템플릿의 제품 ID(또는 게시 ID) 및 Wordpress 기능을 사용하여 이 데이터에 액세스합니다.

// 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 : 관리 주문 페이지에 사용자 지정 메타박스 추가

언급URL : https://stackoverflow.com/questions/37805305/display-product-post-type-advanced-custom-field-on-recent-orders-template-and-ad

반응형