Skip to main content
3 of 3
edited tags
fuxia
  • 107.1k
  • 38
  • 255
  • 459

Saving an array in a single custom field

I have the following array that I want to store in a single custom field.

array("Accounting"=>"Peter", "Finance"=>"Ben", "Marketing"=>"Joe");

I want to store it by typing it in a custom field in wp-admin.

Then I want to retrieve this custom field as an array in a page, with something like

$pos = get_post_meta($post_id, 'pos ', true);

and Output the array with:

foreach($pos  as $x => $x_value) {
    echo $x_value . " head " . $x;
    echo "<br>";
}

My Questions are:

  1. How do I save the array in a single custom field? What exactly do i have to type into the custom field?

  2. How do I retrieve this custom field value as an array in a wordpress template?

Final Solution to problem thx to Ray:

  1. I write the following directly into the custom field in wp admin (or use update_post_meta with json_encode in template)

     {"Accounting":"Peter","Finance":"Ben","Marketing":"Joe"}
    
  2. Retrieve array in custom field with:

     $json_data = get_post_meta($post_id, "my_custom_meta_key", true);
     $arr_data = json_decode($json_data, true);
    
Philip
  • 103
  • 2
  • 11