Displaying ACF field in page or archive head

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!


Solution 1:

The second parameter of the ACF get_field() is required in this case, since you're not in the loop. It is either the post->ID or it's the taxonomy ID where it's {taxonomy_name}_{taxonomy_id} https://www.advancedcustomfields.com/resources/get_field/

Since you want to do this on pages and archives, etc... You need to first determine if it's a single page or an archive, etc.

function acf_header_script() {
    // is it a single post?
    if ( ! is_single() ) {
        // no? get the queried object.
        $object = get_queried_object();
        if ( is_a( $object, 'WP_POST' ) ) {
            $param = $object->ID;
        } else {
            $param = $object->taxonomy . '_' . $object->term_id;
        }
    } else {
        // yes it's a single.
        global $post;
        $param = $post->ID;
    }
    $schema = get_field( 'schema_code', $param );
    // if $schema is not empty.
    if ( $schema ) {
        echo '<script type=application/ld+json>' . json_encode( $schema ) . '</script>';
    }
}
add_action( 'wp_head', 'acf_header_script' );