What I’m trying to do is to optimize the way to store data in my wp_postmeta table.
I need to save multiple relations between posts, and my starting situation was simply this:
add_post_meta($parent_id, 'post_child', $child_id);
In that way I needed to use a database row for each relation.
Considering that the same parent can be associated to multiple children, I was trying to figure it out what could be a good array configuration, and I got to something like this (but I’m still not sure is the best way):
array(
array(
parent => 121,
child => 122
),
array(
parent => 121,
child => 122
),
array(
parent => 121,
child => 123
),
...
);
Then, I tried with this code:
if ($post_relations = get_post_meta($book_id, 'post_relations', true)) {
$post_relations[] = array("parent" => $parent_id, "child" => $child_id);
update_post_meta($book_id, 'post_relations', $post_relations);
} else {
$post_relations[] = array("parent" => $parent_id, "child" => $child_id);
add_post_meta($book_id, 'post_relations', $post_relations);
}
But the result I get in the meta_value field seems to be different to the result I was expecting:
a:2:{
i:0;a:2:{s:6:"parent";i:1;s:5:"child";i:510;}i:1;a:2:{s:6:"parent";i:510;s:5:"child";i:511;}
}
The WordPress functions
update_post_meta()
andadd_post_meta()
both require serializable data;update_post_meta ( int $post_id, string $meta_key, mixed $meta_value, mixed $prev_value = '' )
$meta_value
Must be serializable if non-scalarupdate_post_meta()
It looks like this in the database because those functions
serialize()
the array you’re passing it.Therefore you if you were accessing the data outside of the get_post_meta() function you would have to
unserialize()
the data.I think you should save the relations as one relation per one post meta – saving the relations in the array would make DB queries very difficult.
So, either save your relations as ie post_relations_0, post_relations_1 etc, or, even better, if you plan to do some queries, save the relations in separate table.