rwkiii rwkiii - 3 months ago 12
MySQL Question

Associative arrays in HTML forms using WordPress post meta data functions

I have a collection of objects that need to be saved/retrieved in wp_postmeta table of a custom post type.

Example structure:

array(
array(
'firstname' => 'Johnny',
'middlename' => 'William'
),
array(
'firstname' => 'Jane',
'middlename' => 'Alice'
)
)


I would like to be able to iterate through the objects like this:

$children = get_post_meta( $postid, '_children', true);

$arrlength = count($children);
for($x = 0; $x < $arrlength; $x++)
{
echo '<input type="text" name="_children[][firstname]" id="_children[][firstname]" value="' . $meta_values['_children'][0][$x][firstname] . '" /><br />';
echo '<input type="text" name="_children[][middlename]" id="_children[][middlename]" value="' . $meta_values['children'][0][$x][middlename] . '" /><br />';
}


I don't think the above is correct. I'm trying to get the posted data saved in
save_post
action with:

function test_meta_save( $post_id ) {

// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ '_children_nonce' ] ) && wp_verify_nonce( $_POST[ '_children_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';

// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
if( isset( $_POST[ '_children' ] ) ) {
update_post_meta( $post_id, '_children', array_map( 'sanitize_text_field', $_POST[ '_children' ] );
}
}
add_action( 'save_post', 'test_meta_save' );


I know the above isn't correct either.

Answer

Here you have the same problem that in your last question but this time with get_post_meta() where last argument should be false. because you are reading/creating arrays values and NOT strings values.

In your code:

$children = get_post_meta( $postid, '_children', true);

You need to remove last argument in your get_post_meta() function, as default value is false.
Instead you will have:

$children = get_post_meta( $postid, '_children');

$arrlength = count($children);
for($x = 0; $x < $arrlength; $x++)
{
    echo '<input type="text" name="_children[][firstname]" id="_children[][firstname]" value="' . $meta_values['_children'][0][$x][firstname] . '" /><br />';
    echo '<input type="text" name="_children[][middlename]" id="_children[][middlename]" value="' . $meta_values['children'][0][$x][middlename] . '" /><br />';
}

References:

Comments