Home Forums General Issues Displaying ACF field in page head (JSON script)


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' );
  • I missed that, thanks a lot!

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.