vigogirl
vigogirl

Reputation: 53

ACF, post object in woocommerce Cart

I hope it's a dumb question, but I can't find a smart solution at the moment.

I've got a custom field in my products page - which is a Relationship field - and I'd like to display a field of my RF for every product in my cart page.

More specifically: I have a product associated with a brand. The brand has a 'shipping time' field.

At the moment my function is partially working, in the sense that it displays the request value, but ONLY for the first item in the cart. That's my code in function.php

add_filter( 'woocommerce_get_item_data', 'wc_add_shipping_to_cart', 10, 2 );
function wc_add_shipping_to_cart( $cart_data, $cart_item ) 
{ 

$custom_shipping = array();

if( !empty( $cart_data ) )
    $custom_shipping = $cart_data;

// Get the product ID
$product_id = $cart_item['product_id'];
$custom_field_value = get_post_meta( $product_id, 'brand_select', true );
$display_brand_shipping = get_field('shipping_time_brand', $custom_field_value); 

if( $custom_field_value = get_post_meta( $product_id, 'brand_select', true ) )
    $custom_shipping[] = array(
        'name'      => __( 'Shipping', 'woocommerce' ),
        'value'     => $display_brand_shipping,
        'display'   => $display_brand_shipping,
    );

return $custom_shipping; }

Could you help me?

Upvotes: 2

Views: 684

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254212

Your code is not testable as is not possible to reproduce your issue related to product custom field and ACF fields, but it can be simplified this way:

add_filter( 'woocommerce_get_item_data', 'wc_add_shipping_to_cart', 10, 2 );
function wc_add_shipping_to_cart( $cart_item_data, $cart_item ) 
{ 
    if( $brand_select = get_post_meta( $cart_item['product_id'], 'brand_select', true ) ) {
        if( $shipping_time = get_field('shipping_time_brand', $brand_select ) ) {
            $cart_item_data[] = array(
                'name'      => __( 'Shipping', 'woocommerce' ),
                'value'     => $shipping_time,
            );
        }
    }
    return $cart_item_data;
}

Code goes in function.php file of your active child theme (or active theme).

Upvotes: 1

Related Questions