Woocommerce:结帐订单评论字段中的订单摘要(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 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
            }
        }

这是一个表,但我希望表中的文本显示在字段中,如果不是表.

最佳答案 由于您的问题不是很详细,所以在这里您将获得一个示例,该示例将在Order comments checkout字段中显示所有产品标题:

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;
}

代码位于活动子主题(或主题)的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)

代码经过测试和运行.

点赞