Home › Forums › General Issues › Displaying ACF field in page head (JSON script)
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' );
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”)
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.