Create a [today] shortcode with a date format

Description: Make a shortcode [today] which prints the date in the format d F Y. It should also accept an attribute: [today format="Y-m-d"].

Hint:

  • Use add_shortcode() and shortcode_atts().
  • Return the text, do not echo it. Use wp_date() for the date.

Solution

add_shortcode( 'today', function ( $atts ) {
	$a = shortcode_atts( array( 'format' => 'd F Y' ), $atts, 'today' );
	return esc_html( wp_date( $a['format'] ) );
} );

echo 'Default: ' . ( strlen( do_shortcode( '[today]' ) ) > 0 ? 'works' : 'empty' ) . "\n";
echo 'Format Y-m-d has the right shape: ' . ( preg_match( '/^\d{4}-\d{2}-\d{2}$/', do_shortcode( '[today format="Y-m-d"]' ) ) ? 'yes' : 'no' );
Output

Default: works
Format Y-m-d has the right shape: yes

How it works

  • shortcode_atts() merges the given attributes with the defaults.
  • wp_date() prints the date in the timezone of the site.
  • The output changes every day, so the test checks its shape, not the exact text.

Read Shortcode API.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.