繁体   English   中英

如何在 WooCommerce 结帐页面上显示自定义产品字段?

[英]How to display custom product field on WooCommerce checkout page?

我试图在结帐页面上显示自定义产品字段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;
}

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

您的代码中也有一些错误。 尝试使用位于结帐表单内的钩子尝试以下操作,就在帐单字段之前(假设存在自定义产品字段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 文件中。 它应该更好地工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM