【问题标题】:How to display custom product field on WooCommerce checkout page?如何在 WooCommerce 结帐页面上显示自定义产品字段?
【发布时间】:2019-08-12 19:20:24
【问题描述】:

我正在尝试在结帐页面上显示自定义产品字段 checkout_name,但我似乎无法弄清楚如何。我正在关注here 的结帐挂钩视觉指南。

add_action( 'woocommerce_checkout_before_customer_details', 'custom_before_checkout_form', 10 );
function custom_before_checkout_form( $cart_data ){
    $meta_key = 'checkout_name';

    $product_id = $cart_item['product_id'];

    $meta_value = get_post_meta( $product_id, $meta_key, true );

    if( !empty( $cart_data ) )
        $custom_items = $cart_data;

    if( !empty($meta_value) ) {
        $custom_items[] = array(
            'key'       => __('Store Name', 'woocommerce'),
            'value'     => $meta_value,
            'display'   => $meta_value,
        );
    }
    return $custom_items;
}

【问题讨论】:

  • 自定义结帐字段必须在结帐表单内部。如果不是,则不会在提交时发布字段值。
  • 我明白了,woocommerce_before_checkout_billing_form 会在表格内吗?我也试过那个钩子,但它不起作用。我希望显示帐单详细信息周围的字段,而不是订单详细信息。
  • 请查看Woocommerce template checkout/form-checkout.php 代码...您将看到<form> 标记内部(之后)有哪些钩子... 注意: 模板@987654323 @ 和 checkout/form-shipping.php 在其中被调用(还有其他一些),以获取信息。
  • 好像woocommerce_before_checkout_billing_form 在里面还是我遗漏了什么?
  • 但在“form”标签之后也显示了钩子:woocommerce_checkout_before_customer_details。因此,如果不可能的话,最好在此处显示该字段,然后在 woocommerce_before_checkout_billing_form

标签: php wordpress woocommerce hook-woocommerce


【解决方案1】:

自定义结帐字段需要在结帐表单中。如果不是,则不会在提交时发布字段值。

您的代码中也存在一些错误。尝试以下操作,而不是使用位于结帐表单内的钩子,就在计费字段之前(假设自定义产品字段 checkout_name 存在)

add_action( 'woocommerce_checkout_before_customer_details', 'custom_before_checkout_form' ); 
function custom_before_checkout_form(){
    // Loop though cart items 
    foreach ( WC()->cart->get_cart() as $item ) { 
        // Get the WC_Product Object 
        $product = $item['data'];

        echo '<div align="center">' . $product->get_meta( 'checkout_name' ) . '</div><br>'; 
    }
}

代码在您的活动子主题(或活动主题)的functions.php 文件中。它应该更好地工作。

【讨论】:

    猜你喜欢
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    相关资源
    最近更新 更多