我希望在结帐时在一个字段中显示一个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 ) . ' '; ?>
</td>
</tr>
<?php
}
}
这是一张桌子,但如果不是桌子,我希望表格中的文字显示在字段中。
答案 0 :(得分:1)
由于您的问题不是很详细,因此您可以在订单评论结帐字段中显示所有产品标题的示例:
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
...
您可以轻松输出产品数量和购物车对象中的所有类型的数据......您只需要在问题中明确定义要输出的内容以及的方式(不要忘记这必须是原始数据)喜欢,如在文本区域中输出的那样) ...
代码经过测试并有效。