The more cleaner way of adding the custom data to your site’s <head>
is to use a custom function, which you hook to a relevant action. In this case you could for example utilize the wp_head
action. Like so,
// this goes to functions.php file
add_action('wp_head', 'insert_my_page_schema');
function insert_my_page_schema() {
// only execute the code if on a single page
if ( ! is_page() ) { // modify condition as needed
return;
}
// do we have any saved schema meta
$schema = get_post_meta( get_the_ID(), 'schema', true);
if ( ! $schema ) {
return;
}
// add schema markup to the page head
echo esc_html($schema); // escape output to prevent any unintended html injections
// or if needed, format_my_page_schema($schema);
}
// optional helper function for formatting the schema output
function format_my_page_schema($schema) {
// format the schema, if needed
return $schema;
}
Also, is it a problem that I have different schemas on each page, but
each custom field is named ‘schema’?
Each page can have its own schema meta data saved with the schema
meta key. There’s a problem, if you have multiple custom fields for a page with each of them having the same meta key, i.e. every schema input has name="schema"
. But if the field names are in array format, name="schema[]"
, and you’re saving the data as an array, then there shouldn’t be a problem. If the data is saved as an array, then you need to modify the output function to handle the array accordingly.