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

Has*_*san 3 php wordpress checkout cart woocommerce

我一直在寻找互联网上的解决方案,但找不到任何适当的解决方案.我在我的产品页面中使用了几个自定义字段,例如'Minimum-Cooking-Time','Food-Availability'等.所以,我想在我的购物车和结帐页面中显示这个自定义字段的价值.

我在功能文件和编辑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; 

}
Run Code Online (Sandbox Code Playgroud)

但是,这显示标签'Cook Time',但旁边没有显示任何值.

任何帮助,将不胜感激.

谢谢.

Loi*_*tec 7

您的问题在于get_post_meta()函数的最后一个参数设置为true,因此您将自定义字段值作为字符串获取.
然后你正在使用预期数组不是字符串值array_map()PHP函数.

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

您也可以$product_id通过get_post_meta()一种非常简单的方式将您在函数中使用的函数设置为第一个参数.

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

// 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;
}
Run Code Online (Sandbox Code Playgroud)

代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中.

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