Woocommerce:结帐订单评论字段中的订单摘要 (PHP)

Woocommerce: Order Summary in checkout Order comments field (PHP)

我希望结账时在字段中显示 woocommerce 订单的订单摘要。我可以在字段中放置纯文本,但是当我尝试添加挂钩时它会抛出错误代码。这是将默认文本添加到字段的代码。位于 functions.php:

add_filter( 'woocommerce_checkout_fields' , 'default_values_checkout_fields' );

function default_values_checkout_fields( $fields ) {

$fields['order']['order_comments']['default'] = ' I would like the hook here ';

return $fields;
}

此代码在结帐时输出 table:

<table class="shop_table woocommerce-checkout-review-order-table">

<tbody>
    <?php
        do_action( 'woocommerce_review_order_before_cart_contents' );

        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            $_product     = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );

            if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_checkout_cart_item_visible', true, $cart_item, $cart_item_key ) ) {
                ?>
                <tr class="<?php echo esc_attr( apply_filters( 'woocommerce_cart_item_class', 'cart_item', $cart_item, $cart_item_key ) ); ?>">
                    <td class="product-name">
                        <?php echo apply_filters( 'woocommerce_cart_item_name', $_product->get_title(), $cart_item, $cart_item_key ) . '&nbsp;'; ?>
                                                                            </td>
                </tr>
                <?php
            }
        }

它是 table,但如果不是 table,我希望 table 中的文本显示在字段中。

由于您的问题不是很详细,这里有一个示例,它将在订单评论结帐字段中显示所有产品标题:

add_filter( 'woocommerce_checkout_fields' , 'custom_order_comments_checkout_fields' );
function custom_order_comments_checkout_fields( $fields ) {

    if ( !WC()->cart->is_empty()):

    $output = '';
    $count = 0;
    $cart_item_count = WC()->cart->get_cart_contents_count();

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ):

        $count++;

        // Displaying the product title
        $output .= 'Product title: ' . $cart_item['data']->post->post_title;

        // New line (for next item)
        if($count < $cart_item_count)
            $output .= '
';

    endforeach;

    $fields['order']['order_comments']['default'] = $output;

    endif;

    return $fields;
}

代码进入您的活动 child 主题(或主题)的 function.php 文件。或者在任何插件 php 文件中。

此代码将显示在结帐订单评论字段中,如下所示:

Product title: My Product title 1
Product title: My Product title 2
...

You can easily output product quantity and all kind of data that is in the cart object… You have just to clearly define in your question what you want to output and how (without forgetting that this has to be raw data like, as is outputted in a text area field)

代码已经过测试并且可以工作。