Hi everyone,
I would like to use an ACF field to inject Schema merkup to a few specific pages on my WordPress website. Some of them are custom taxonomies or custom post types.
After a two hour research on the topic, I am still stuck.
I have created a text area field called “schema_code” and entered the desired Schema markup for some of my sub pages.
I currently use this code in my functions.php which does not do anything:
function acf_header_script() {
$schema = get_field('schema_code');
echo '<script type=application/ld+json>' . json_encode($schema_code) . '</script>';
}
add_action ( 'wp_head', 'acf_header_script' );
What am I missing here? Thanks a lot!
If you are actually entering json code into the field then json_encode()
is not necessary.
When getting fields outside of “The Loop” you must supply the post ID to get the field from
function acf_header_script() {
$queried_object = get_queried_object();
if (is_a($queried_object, 'WP_Post')) {
$schema = get_field('schema_code', $queried_object->ID);
echo '<script type=application/ld+json>' . $schema_code . '</script>';
}
}
add_action ( 'wp_head', 'acf_header_script' );
I missed that, thanks a lot!
function acf_header_script() {
$queried_object = get_queried_object();
if (is_a($queried_object, 'WP_Post')) {
$schema = get_field('schema_code', $queried_object->ID);
echo '<script type=application/ld+json>' . $schema_code . '</script>';
}
}
add_action ( 'wp_head', 'acf_header_script' );
When I want to use it on a Page (e.g. on “Home”), how I must fix this code?
(It doesn´t work on Homepage if I use this code + ACF Field “schema_code”)