I’m trying to fill WP SEO Structured Data Schema fields with add_post_meta function and it doesn’t work properly. I checked one of the posts that’s added from WordPress admin panel and it was saved like this:
a:12:{s:6:"active";s:1:"1";s:8:"headline";s:13:"aaa";s:16:"mainEntityOfPage";s:37:"http://1.test/?p=83&preview=true";s:6:"author";s:1:"c";s:5:"image";s:2:"91";s:13:"datePublished";s:1:"d";s:12:"dateModified";s:1:"e";s:9:"publisher";s:1:"f";s:14:"publisherImage";s:2:"91";s:11:"description";s:1:"g";s:11:"articleBody";s:1:"h";s:19:"alternativeHeadline";s:1:"i";}
looks like this _schema_article is the parent of _schema_article[headline] which I’m trying to save. this is my code:
<?php
require_once("wp-load.php");
$my_post = array(
'post_title' => "title",
'post_content' => "content",
'post_status' => 'publish',
'post_author' => 1,
);
$remote_id = wp_insert_post($my_post);
echo $remote_id;
add_post_meta($remote_id, "_schema_article[headline]", "aaa", true);
how can I create something like this JSON-like example above with add_post_meta or other WordPress functions?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
This is the PHP serialization format, and is used to serialize arrays for storage in the database. Core WordPress functions take care of this process for you. You just need to use an array as the value.
For example, this:
$schema_article = array(
'headline' => 'aaa',
);
update_post_meta( $remote_id, '_schema_article', $schema_article );
Will save this value:
a:1:{s:8:"headline";s:3:"aaa";}
If you want to see the original array for a value, get_post_meta() will unserialize it for you.
For example, this:
$schema_article = get_post_meta( $remote_id, '_schema_article', true );
Will return (as seen via var_dump()):
array(1) {
["headline"]=>
string(3) "aaa"
}
So when saving the value you need to mimic the original array format. I would share what that is for your example, but it cannot be unserialized because it has been corrupted by editing the value by hand.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0