【问题标题】:Display Custom Field's Value in Woocommerce Cart & Checkout items在 Woocommerce 购物车和结帐项目中显示自定义字段的值
【发布时间】:2017-10-09 03:28:27
【问题描述】:

我一直在互联网上寻找解决方案,但找不到任何合适的解决方案。我在我的产品页面中使用了几个自定义字段,例如“最短烹饪时间”、“食物可用性”等。所以,我喜欢在我的购物车和结帐页面中显示这个自定义字段的值。

我在函数文件中尝试了 sn-ps 并编辑了 woocommerce 购物车文件。我已经尝试了几个代码,但它们没有从我的自定义字段中提取任何数据。

正如您在下面的屏幕截图中看到的,我想在每个产品的黑色矩形区域中显示“最短烹饪时间”:

我使用了以下代码:

add_filter( 'woocommerce_get_item_data', 'wc_add_cooking_to_cart', 10, 2 ); 
function wc_add_cooking_to_cart( $other_data, $cart_item ) { 
    $post_data = get_post( $cart_item['product_id'] );  

    echo '<br>';
    $Add = 'Cook Time: ';
    echo $test;
    $GetCookTime = get_post_meta( $post->ID, 'minimum-cooking-time', true );

    $GetCookTime = array_filter( array_map( function( $a ) {return $a[0];}, $GetCookTime ) );

    echo $Add;
    print_r( $GetCookTime );

    return $other_data; 

}

但是,这会显示标签“Cook Time”,但旁边没有显示任何值。

任何帮助将不胜感激。

谢谢。

【问题讨论】:

    标签: php wordpress woocommerce checkout cart


    【解决方案1】:

    您的问题出在 get_post_meta() 函数中,该函数的最后一个参数设置为 true,因此您获得了一个自定义字段值作为字符串
    然后你在 array_map() PHP 函数之后使用 需要一个数组,但 不是一个字符串值

    我认为您不需要使用 array_map() 函数,因为 get_post_meta() 函数将最后一个参数设置为 true 将输出一个字符串而不是未序列化的数组。

    您还可以将您在get_post_meta() 函数中使用的$product_id 设置为第一个参数,方式非常简单。

    所以你的代码应该这样工作:

    // Render the custom product field in cart and checkout
    add_filter( 'woocommerce_get_item_data', 'wc_add_cooking_to_cart', 10, 2 );
    function wc_add_cooking_to_cart( $cart_data, $cart_item ) 
    {
        $custom_items = array();
    
        if( !empty( $cart_data ) )
            $custom_items = $cart_data;
    
        // Get the product ID
        $product_id = $cart_item['product_id'];
    
        if( $custom_field_value = get_post_meta( $product_id, 'minimum-cooking-time', true ) )
            $custom_items[] = array(
                'name'      => __( 'Cook Time', 'woocommerce' ),
                'value'     => $custom_field_value,
                'display'   => $custom_field_value,
            );
    
        return $custom_items;
    }
    

    代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件中。

    此代码功能齐全且经过测试。

    【讨论】:

    • 嗨@LoicTheAztec,我要如何吻你?它的工作就像魅力:D .. 非常感谢您的宝贵时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 2019-07-21
    • 2018-07-25
    相关资源
    最近更新 更多