Display custom field metadata encoded multidimentional array value in WordPress

24 views Asked by At

Trying to display a Wordpress custom field meta_key value.

The data is saved as a WordPress custom field meta_key value

$data = get_post_meta( get_the_ID(), 'data', false);
print_r($data); 



Array (
[0] => [
{
"title":"Title A",
"date":"2024-06-06",
"venue":"Venue X"
},
{
"title":"Title B",
"date":"2010-08-08",
"venue":"Venue Y"
}
]
)

The code I am using

<?php
$data = get_post_meta( get_the_ID(), 'data', false);
$size = count($data[0]);
$i = 0;
for( $j = 0; $j < $size; $j++ ) 
{ 
?>
<p>Title: <?php echo $data[$i][$j]['title']; ?></p>
<p>Date: <?php echo $data[$i][$j]['date']; ?></p>
<p>Venue: <?php echo $data[$i][$j]['venue']; ?></p>
<?php 
} 
?>

The output I am getting

Title: [

Date: [

Venue: [

Any pointers on where its going wrong.

1

There are 1 answers

0
LoicTheAztec On

To get the data displayed, you need to:

  • Set the 3rd argument from get_post_meta() function to true instead of false,
  • Use json_decode() function on it (as it's JSON encoded),
  • Use a foreach loop, instead of a for loop.

Try the following:

$meta = get_post_meta( get_the_ID(), 'data', true);
$data = json_decode($meta);

foreach ( $data as $object ) { 
    if ( isset($object->title) ) {
        printf('<p>%s: %s</p>', __('Title'), $object->title );
    }
    if ( isset($object->date) ) {
        printf('<p>%s: %s</p>', __('Date'),  $object->date );
    }
    if ( isset($object->venue) ) {
        printf('<p>%s: %s</p>', __('Venue'), $object->venue );
    }
} 

It should work.