2

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

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();
  • This is the better answer :P – sMyles Jan 7 '17 at 1:18
0

Usually, custom fields are save from form input. If you want to save an array like yours, you can create a metabox on the post edit screen.

This metabox should display input with the same name, something like that

<input type="text" name="pos[Accounting]" value=""/>
<input type="text" name="pos[Finance]" value=""/>
<input type="text" name="pos[Marketing]" value=""/>

The way you suggest to display looks good.

You can find more details to display and save metaboxes with add_meta_boxes action et add_meta_box()

hope it gives you some hints !

0

Sounds like you want to be able to input these values from the core WordPress custom fields metabox:

enter image description here

To do this I would use a custom format, and then convert it when the post is saved.

// This function converts "Accounting,Peter|Finance,Ben|Marketing,Joe" format
// to array("Accounting"=>"Peter", "Finance"=>"Ben", "Marketing"=>"Joe");
function smyles_convert_custom_format_to_array( $val ){

    $employee_data = array();

    // Create array with | as separator
    $parts = explode( '|', $val );

    if( ! empty( $parts ) ){

        // Loop through each one
        foreach( $parts as $part ){

            // Split again based on comma
            $part_array = explode( ',', $part );

            // As long as there is a value, let's add it to our employee array
            if( ! empty( $part_array[0] ) && ! empty( $part_array[1] ) ){

                // First value in array will be our key, second will be the value
                $employee_data[ $part_array[0] ] = $part_array[1];
            }

        }

    }

    return $employee_data;
}

You then need to add an action to update the meta after converting the custom format with the function above:

// Add a custom action on save post so we can convert our custom format
add_action( 'save_post', 'smyles_save_post_format_custom_field', 99, 3 );
// This function will update the post meta with an array instead of using our custom format
function smyles_save_post_format_custom_field( $id, $post, $update ){

    $custom_field = 'employees';

    // Change `post` below to something else if using custom post type
    if( $post->post_type != 'post' ) {
        return;
    }

    // Only try to process if a value exists
    if( ! empty( $_POST[ $custom_field ] ) ){
        $value = smyles_convert_custom_format_to_array( $_POST[ $custom_field ] );
    } else {
        // Otherwise set $value to empty value, meaning custom field was deleted or has an empty value
        $value = array();
    }

    update_post_meta( $id, $custom_field, $value, true );

}

When you want to pull these values, just use this:

// Arrays are stored serialized, so let's get that first
$value = get_post_meta( $post_id, 'employees', true);

Voila! Profit!

  • maybe_unserialize is already used by get_metadata, it shouldn't be necessary to serialize / unserialize anything when using the meta data API. – Milo Jan 7 '17 at 0:56
  • @Milo yeah you're right, not sure why I thought you had to unserialize ... hmm long day hah! Updated the answer – sMyles Jan 7 '17 at 1:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.