I am creating the following code to display open graph meta data in the header of my single.php page

add_action('wp_head', 'mycode_add_og_meta_tags', 5);

function mycode_add_og_meta_tags () {

    <meta property="og:type" content="article"/>

    <meta property="og:title" content="<?php the_title(); echo ' ('; _e('Source:', 'mydomain'); the_author(); echo')'; ?>"/>

    <meta property="og:description" content="<?php echo strip_tags(get_the_content(), '<p>'); ?>"/>

    <?php if(has_post_thumbnail()) : ?>
    <meta property="og:image" content="<?php the_post_thumbnail_url('single') ?>"/>
    <?php endif; ?>


However, both the_author() and get_the_content() do not return any data; yet the_title() and the_post_thumbnail_url() do return data.

Moreover, in the 'body' of the single.php file, I am able to retrieve all the aforementioned information.

I am suspecting that this has to do being inside the loop, so my questions are:

  1. If it has nothing to do with the loop, how can I retrieve the missing aforementioned values?

  2. If my approach is incorrect because I am retrieving that information outside the loop, then:

    • How come title and thumbnail work?

    • How can I set the open graph meta data (og), before getting into the loop?


1 Answer 1


get_the_content and the_author have to be in a loop so you would need to use other functions to get the content you need

global $wp_query;
$post = $wp_query->post;
$page_id = $post->ID; // page ID
$page_object = get_page( $page_id ); // page stuff
$author_id = $post->post_author; // author ID

$page_content = $page_object->post_content;
$author_name = get_the_author_meta( 'display_name', $author_id);
  • hmmm, $post is set in the loop so not sure you idea will work at all Commented Jun 8, 2016 at 18:18
  • oops, edited to use $wp_query Commented Jun 8, 2016 at 18:36
  • Both this solution: global $wp_query, and your original solution: global $post, worked
    – Greeso
    Commented Jun 8, 2016 at 18:49
  • Simply use get_post to be on safe side. Also check if you are on single page or not!
    – Sumit
    Commented Jun 8, 2016 at 18:50
  • my fault for being vague. I guess the first problem is with the OP assumption that there is even a post that can be looked at. Search pages might not have any results at all, and for such archive pages he will probably want to have something else in any case. get_queried_object is kinda more "neutral" way to get the object being queried without relying on the loop related global variables; Commented Jun 8, 2016 at 19:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.