How to display date in wordpress pages

The default Twenty Twelve theme which comes with wordpress and many other themes display creation date in wordpress posts but do not display any date (creation of modified) in wordpress pages. For many pages like “about us”, “contact us”, etc. displaying date is not relevant. But sometimes we want to display date in pages.

When would one want to display date in wordpess pages

Here are some cases where displaying date may be relevant.

  1. Pages like some online tools/utilities, tutorials, etc. may be more useful with modification date (date page was last edited on).
  2. Some content you may not want to put in RSS. The one easy option is to create these as pages instead of posts. And then it may be useful for users to have a modification date on some of these pages.

How to display modification date

In case you want to display modification date only on certain wordpress pages, you can do it using various approaches. Here are some of them:

  1. Define a custom field and set it of for pages where you want to display modification date.
  2. Use some url match approach. e.g. you may want to display modification date for all users beginning with /foo/. You can use $_SERVER[‘REQUEST_URI’] to get access to the url. Here is how the php code will look like:
    if (preg_match('#^/foo/#i', $_SERVER["REQUEST_URI"])) {
      // display date logic...
    }

For this article we’ll use custom field approach (with custom field name showModifiedDate). Now look for the page template in your theme. Assuming you have a separate template for page in your theme, one approach is define a shortcode for displaying modification date. Here is wordpress plugin pseudocode for it:

function my_entry_published_shortcode( $attr ) {
  global $post;
  if (!is_page()) {
    return "";
  }
  $show_modified_date_value = get_post_meta($post->ID, 'showModifiedDate', true);
  if (empty($show_modified_date_value) || !in_array($show_modified_date_value, array('true', '1'))) {
    return "";
  }
  $date = sprintf( '<time class="entry-date" datetime="%1$s">%2$s</time>',
      esc_attr( get_the_date( 'c' ) ),
      esc_html( get_the_date() )
  );
  return $date;  
}
add_shortcode( 'entry-modified', 'my_entry_published_shortcode' );

Now you an add short code [modified-date] to the appropriate place in the template. Modify the code appropriately if you want to add some text around it. You may want to take care of localization also in that case.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments