首页 文章

在Woocommerce购物车和结帐项目中显示自定义字段的 Value

提问于
浏览
3

我一直在寻找解决方案一段时间在互联网上,但找不到任何适当的解决方案 . 我在我的产品页面中使用了几个自定义字段,例如“最少烹饪时间”,“食物供应”等 . 所以,我想在我的购物车和结帐页面中显示此自定义字段的 Value .

我在功能文件和编辑woocommerce购物车文件中尝试了片段 . 我尝试了几个代码,但他们没有从我的自定义字段中提取任何数据 .

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

from the picture

我使用了以下代码:

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; 

}

但是,这显示标签'库克时间',但没有显示任何值 .

任何帮助,将不胜感激 .

谢谢 .

1 回答

  • 5

    您的问题在get_post_meta()函数中,最后一个参数设置为 true ,因此您获得自定义字段值 as a string .
    然后你正在使用 expecting an array 的PHP函数 expecting an arrayNOT a string value .

    我认为你不需要使用array_map()函数作为get_post_meta()函数,并将last参数设置为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文件中,或者放在任何插件文件中 .

    This code is fully functional and tested.

相关问题