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);
    

3 Answers
3

You can json_encode() it which will make it a string that you can put into a custom field then just ensure you json_decode() it to bring it back to an object or json_decode($data, true) to bring it back as an array

$arr = array("Accounting"=>"Peter", "Finance"=>"Ben", "Marketing"=>"Joe");
update_post_meta($post_id, "my_custom_meta_key", json_encode($arr));
$json_data = get_post_meta($post_id, "my_custom_meta_key", true); // true to ensure it comes back as a string and not an array
$arr_data = json_decode($json_data, true); // 2nd parameter == true so it comes back as an array();

Leave a Reply

Your email address will not be published. Required fields are marked *