WordPress at a glance

the_date() WP 0.71

Displays or Retrieve the date of the current post was written. Works with a group of posts (published on the same day).

Uses only in a WordPress loop.

Works with a group of posts means that for posts published on the same day, the date will be displayed only for the first post, even if the function is called several times for each post. I.e., for each next post in the loop, this function checks on what day current post was published, and if the date of the current post and the previous one are the same, then the date of current post will not be displayed.

HTML output can be filtered with the_date hook. Date string output can be filtered with 'get_the_date'.

Affects on the return value of is_new_day() when both functions are used in the same code construction.

Notes:

  • Global. String/Int/true/false. $currentday
  • Global. String/Int/true/false. $previousday
Works based on: get_the_date(), is_new_day()
✈ 1 time = 0.000604s = slow | 50000 times = 1.38s = fast PHP 7.2.5, WP 4.9.6
Hooks from function:
Return

String/null.

  • String if retrieving.
  • null when the result is displayed on the screen.

Usage

<?php the_date( $d, $before, $after, $echo ); ?>
$d(string)
PHP date format. date_format option if not specified. See possible formats.
Default: ''
$before(string)
Text/HTML before the date.
Default: ''
$after(string)
Text/HTML after the date.
Default: ''
$echo(true/false)
Whether to echo the date or return it. true - echo result.
Default: true

Examples

#1 Output the date in the format of WordPress settings

<p>Published at <?php the_date(); ?></p>

#2 Output the date in the 2007-07-23 format and wrap it in the <h2> tag

<?php the_date( 'Y-m-d', '<h2>', '</h2>' ); ?>

Displays something like this: <h2>2018-05-12</h2>

#3 Return the date to variable, but not display it

$date = the_date( 'Y-m-d', '', '', 0 ); //> 2018-05-12

Code of the_date: wp-includes/general-template.php VER 4.9.8

<?php
function the_date( $d = '', $before = '', $after = '', $echo = true ) {
	global $currentday, $previousday;

	if ( is_new_day() ) {
		$the_date = $before . get_the_date( $d ) . $after;
		$previousday = $currentday;

		/**
		 * Filters the date a post was published for display.
		 *
		 * @since 0.71
		 *
		 * @param string $the_date The formatted date string.
		 * @param string $d        PHP date format. Defaults to 'date_format' option
		 *                         if not specified.
		 * @param string $before   HTML output before the date.
		 * @param string $after    HTML output after the date.
		 */
		$the_date = apply_filters( 'the_date', $the_date, $d, $before, $after );

		if ( $echo )
			echo $the_date;
		else
			return $the_date;
	}
}

Related Functions

From tag: WP Loop

More from tag: date time

More from category: Posts, pages...

More from Template Tags: Posts, Pages, ...

No comments
    Hello, !     Log In . Register