【问题标题】:WooCommerce ACF Display custom meta data on Cart and Checkout pageWooCommerce ACF 在购物车和结帐页面上显示自定义元数据
【发布时间】:2016-10-30 18:40:29
【问题描述】:

我想同时在 WooCommerce 购物车和结帐页面中显示使用 Advanced Custom Fields 插件创建的自定义字段的值。

我在我的主题的 functions.php 页面中使用以下代码,该代码仅显示在产品的单个页面中:

add_action( 'woocommerce_before_add_to_cart_button', 'add_custom_field', 0 );

function add_custom_field() {
    global $post;

  echo "<div class='produto-informacoes-complementares'>";
  echo get_field( 'info_complementar', $product_id, true );
  echo "</div>";

    return true;
}

提前感谢大家提供的所有帮助,请原谅我的英语。

【问题讨论】:

    标签: php wordpress woocommerce advanced-custom-fields product


    【解决方案1】:

    我无法在您的网上商店进行测试,所以我不能完全确定:

    在单个产品页面中显示自定义字段值(您的功能)

    add_action( 'woocommerce_before_add_to_cart_button', 'add_custom_field', 0 );
    
    function add_custom_field() {
        global $product;             // Changed this
    
        // Added this too (compatibility with WC +3) 
        $product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
    
        echo "<div class='produto-informacoes-complementares'>";
        echo get_field( 'info_complementar', $product_id );
        echo "</div>";
    
        return true;
    }
    

    (更新)将此自定义字段存储到购物车和会话中:

    add_filter( 'woocommerce_add_cart_item_data', 'save_my_custom_product_field', 10, 2 );
    
    function save_my_custom_product_field( $cart_item_data, $product_id ) {
    
        $custom_field_value = get_field( 'info_complementar', $product_id, true );
    
        if( !empty( $custom_field_value ) ) 
        {
            $cart_item_data['info_complementar'] = $custom_field_value;
    
            // below statement make sure every add to cart action as unique line item
            $cart_item_data['unique_key'] = md5( microtime().rand() );
        }
        return $cart_item_data;
    }
    

    (更新)在购物车和结账时呈现元数据:

    add_filter( 'woocommerce_get_item_data', 'render_meta_on_cart_and_checkout', 10, 2 );
    
    function render_meta_on_cart_and_checkout( $cart_data, $cart_item ) {
        $custom_items = array();
        // Woo 2.4.2 updates
        if( !empty( $cart_data ) ) {
            $custom_items = $cart_data;
        }
        if( isset( $cart_item['info_complementar'] ) ) {
            $custom_items[] = array( "name" => "Info complementar", "value" => $cart_item['info_complementar'] );
        }
        return $custom_items;
    }
    

    最后 2 个钩子中有一些错误导致它无法正常工作……现在它应该可以工作了。

    【讨论】:

    • Loic 这是一个老钩子名字吗?
    • @Wed 使用的钩子仍在上一个 Woocommerce 版本上工作。
    猜你喜欢
    • 1970-01-01
    • 2018-02-01
    • 2015-03-17
    • 2013-12-13
    • 2019-06-27
    • 2021-09-23
    • 2018-07-25
    • 1970-01-01
    • 2020-11-03
    相关资源
    最近更新 更多