functions – How to save custom made object in an array in a post meta field
I’ve made two custom classes:
I’m making a quite custom calculation of a bunch of things, that I would like to save in an array in a post_meta field.
This is how I save it
$obj1 = new FooBar(); $obj2 = new BarSchizzle(); $obj3 = new FooBar(); $arr = [ 'a_key' => $obj1, 'another_key' => $obj2, 'a_third_key' => $obj3, ]; update_post_meta( $post_ID, 'my_custom_field', $arr ); // I also tried this, with same result // update_post_meta( $post_ID, 'my_custom_field', serialize( $arr ) );
This is how I retrieve the array
$initial_arr = get_post_meta( $post_ID, 'my_custom_field', true ); $arr = unserialize( $initial_arr ); // And this is where the error occurs
I’m getting the error:
unserialize() [function.unserialize]: Error at offset ... (you can read more about it here).
My theory is, that WordPress hasn’t gotten to loading (requiring) my custom classes, when it get’s (and unserializes).
I’ve required the classes by simply slapping them into the
functions.php-file, in the top, like this:
require_once( __DIR__ . '/classes/FooBar.php' ); require_once( __DIR__ . '/classes/BarSchizzle.php' );
… Not inside any hook or anything. It felt a bit sloppy/bad, but it has been working perfectly up until now.
So this leaves me with two questions:
- Do I need to put my require of my custom classes inside a hook, like
- Are there another explanation why WordPress stumbles when it tries to unserialize that
$arr, containing my custom objects?
Leave an answer