1

I want to pull some post/page specific data (author name, post ID, publish time, etc) into header.php to be used in meta tags. I am having trouble figuring out the most efficient way to do this. It is my understanding that I will need to create a loop within header.php to pull this data. How can I go about creating a loop for the current page/post if I don't yet know the ID?

2

Main query is actually processed before template is loaded, so data is available in header (if a little less convenient to use).

You don't actually need loop, get_the_ID() should give you ID for the queried object and most template tags have version that will return you results for that specific ID.

Loop would work just as well, but it's not very common to run it this early.

  • Ah good to know! I think I can get author name and some other info this way, but I can't find a template tag that shows publish date based on ID - is this possible? – Josh Mountain Feb 24 '14 at 17:27
  • @JoshMountain get_the_date() is one of those which (inconsistently) doesn't work for given ID, but you should get the idea how to, looking at its short source – Rarst Feb 24 '14 at 17:30
1

You obviously know the current page/post id. Because loading any template file, the query perform to fetch data of post, page, term or any other thing.

To add information into tag, you should be using wp_head hook. Below is an example -

add_action('wp_head', 'wpse_wp_head');
function wpse_wp_head(){
    // first make sure this is a single post/page
    if( !is_page() || !is_single() )
        return;

    // then get the post data
    $post = get_post();

    echo '<meta name="post_id" value="'. $post->ID .'" />';

    $author = get_user_option('display_name', $post->post_author );
    echo '<meta name="author" value="'. esc_attr( $author ) .'" />';
}
0

This is how I managed to obtain a meta tag for the author on header.php:

  <?php
    if (is_singular()) {
      $post = get_post();
      $autor_fn = get_the_author_meta('first_name',$post->post_author);
      $autor_ln = get_the_author_meta('last_name',$post->post_author);
      if (!empty($autor_fn) && !empty($autor_ln)) {
  ?>
        <meta name="author" content="<?php echo "$autor_fn $autor_ln"; ?>">
  <?php
      }
    }
  ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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