Formatted Date Shortcode With Offsets
Adds a [show_date] shortcode that prints today's date, or a date relative to it such as "+3 days" or "next friday", in any format, for delivery promises, deadlines and offer end dates.
Opens WPIDE on
Code
add_action( 'init', function () {
add_shortcode( 'show_date', function ( $atts ) {
$atts = shortcode_atts( array( 'format' => get_option( 'date_format' ), 'offset' => '' ), $atts, 'show_date' );
$now = new DateTimeImmutable( 'now', wp_timezone() );
if ( '' !== trim( $atts['offset'] ) ) {
$offset = sanitize_text_field( $atts['offset'] );
// Reject text PHP cannot parse instead of letting modify() warn.
if ( false === strtotime( $offset ) ) {
return '';
}
$now = $now->modify( $offset );
}
return '<time datetime="' . esc_attr( $now->format( 'Y-m-d' ) ) . '">' . esc_html( wp_date( $atts['format'], $now->getTimestamp() ) ) . '</time>';
} );
} );
Notes
Example [show_date offset="+2 weekdays" format="l, F j"]; uses the site time zone. Pages cached by a caching plugin show the date they were cached.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.