Correct PHP Syntax and the Arrays in woocommerce

One value is to be populated in the array from the database:

global $post;
	$post_meta_1 =  get_post_meta($post->ID,'_number_field_1',true);
	if(isset($cart_item['custom_data'][1])) {
		$item_data[] = array(
	  'key' => __( 'Addon 1 ', 'woocommerce' ),
		'value'   => wc_clean($post_meta_1),
	  );
	}

But this part is not rendering any result in the front end.
'value' => wc_clean($post_meta_1),

Where are we going wrong? Is there any syntax error or we are going wrong somewhere else?

Are you sure $cart_item['custom_data'][1] is set? Because if it isn’t that value isn’t filled either.

Yes, sure.
Because this is getting printed →

  'key' => __( 'Addon 1 ', 'woocommerce' ),

If we write it like this:

'value' => 'text',

then the text gets published.

However this prints nothing

	'value'   => $post_meta_1,

So it must be this line that has the problem

$post_meta_1 =  get_post_meta($post->ID,'_number_field_1',true);

Is the ID value what you expect it to be?

1 Like

In the other places of the theme it works fine.
I have also defined gloal $post within the function.

But what about in the place where you’re having trouble with it? The fact it works elsewhere is possibly not relevant.

I’ve never liked globals - why don’t you pass it in, like you pass in $cart_item, as a parameter?

How?

Look at your function definition, you can see the two parameters that you pass in to the function. I’d quote the line, but for some reason you’ve posted it as an image, so I can’t.

All you need to do is add another parameter to that list, and add it to each time you call the function. The extra variable / array / object will be available inside the function, and you won’t need to make sure that you always call it $post in your external code.

Presuming that woocommerce will allow that kind of thing, of course.