I'm trying to write my own code for populating JSON-LD Schema code (I'd rather not rely on plugins for this).
For Wordpress posts, one of the key schema elements is author data. So I use get_the_author_meta() function to access it.
This works perfectly fine when it fires in the wp_footer action, but comes up empty when firing in wp_head.
I've checked this in the astra theme as well as twentytwentyone theme.
I stole this code just for demonstration purposes, it's twitter OG card and not Schema but its effectively the same. Forgive me but I can't remember what stackoverlow post I found it in.
In functions.php:
function my_twitter_cards() {
if (is_singular()) {
global $post;
$twitter_user = get_the_author_meta('nickname'); #This is the element that works in wp_footer but not in wp_head, all the other fields seem to work.
$twitter_url = get_permalink();
$twitter_title = get_the_title();
$twitter_excerpt = get_the_excerpt();
$twittercard_image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full');
$twittercard_thumb = $twittercard_image[0];
if (!$twittercard_thumb) {
$twittercard_thumb = 'https://www.example.com/default-image.png';
}
if ($twitter_user) {
echo '<meta name="twitter:creator" value="@' . esc_attr($twitter_user) . '" />' . "\n";
}
echo '<meta name="twitter:card" value="summary" />' . "\n";
echo '<meta name="twitter:url" value="' . esc_url($twitter_url) . '" />' . "\n";
echo '<meta name="twitter:title" value="' . esc_attr($twitter_title) . '" />' . "\n";
echo '<meta name="twitter:description" value="' . esc_attr($twitter_excerpt) . '" />' . "\n";
echo '<meta name="twitter:image" value="' . esc_url($twittercard_thumb) . '" />' . "\n";
echo '<meta name="twitter:site" value="@mhthemes" />' . "\n";
}
}
add_action('wp_head', 'my_twitter_cards'); #swap this out for wp_footer to see the difference.
My theory was that it couldn't access the loop when called in the header, but that doesn't explain why post-specific data is populating (i.e permalink, title, etc), and not the get_the_author_meta data.
Now I can go with it if I just populate the footer, in this application it would be OK, but some things need to be in the header, so I want to figure out why its not working as expected.
Thank you in advance!