How to use a dynamic date in the WordPress editor
Did you know that a dynamic date is used on 99.9% of all sites? Where, you ask? As a rule, in the footer, in the copyright line. But on most sites this part is hardcoded in the theme, where a dynamic date is no problem: <?php echo date( 'Y' ); ?>. In this article we will look at how to add a dynamic date to the content that is edited in the dashboard.
Problem: How to add a dynamic date to Gutenberg, ACF fields, Contact Form 7, etc.?
Solution: Adding the current date or time (day, month, year) to content in WordPress is simple: use a shortcode. Add to functions.php:
<?php
// Dynamic date shortcode
add_shortcode( 'dynamic_date', 'custom_dynamic_date' );
function custom_dynamic_date( $atts ) {
$atts = shortcode_atts( array( 'date' => 'Y' ), $atts );
return esc_html( wp_date( $atts['date'] ) );
}
wp_date() (WordPress 5.3+) uses the time zone from Settings → General. Plain PHP date() in WordPress always returns UTC, so around midnight it can show the wrong day.
In the editor, use the shortcode with any PHP date format:
© [dynamic_date] Company Name → © 2020 Company Name [dynamic_date date="F"] → January [dynamic_date date="F j, Y"] → January 5, 2020
In Gutenberg it works in the Shortcode block and inside a normal paragraph. In ACF WYSIWYG fields it works too.
ACF text and textarea fields
For text fields, add this filter to functions.php:
<?php add_filter( 'acf/format_value/type=text', 'do_shortcode' );
And for textarea fields:
<?php add_filter( 'acf/format_value/type=textarea', 'do_shortcode' );
The filters work when the value is output with get_field() or the_field().
Contact Form 7
For Contact Form 7 forms:
<?php add_filter( 'wpcf7_form_elements', 'do_shortcode' );
Post titles
Shortcodes do not work in titles by default. If you need, for example, “Best offers of [dynamic_date]” in a title, enable them there:
<?php add_filter( 'the_title', 'do_shortcode' );
Keep in mind that the SEO title from Yoast and similar plugins is built separately, so there the shortcode stays as text.
Update (February 2023): With the same Contact Form 7 filter we can also use the ACF shortcode in a form. For example, the submit button title has to be different on every page:
- On the page, create an ACF field, e.g. form_button_title.
- In the Contact Form 7 form settings, write
[submit "[acf field="form_button_title"]"], or put[acf field="form_button_title"]anywhere in the form markup. - Add
add_filter( 'wpcf7_form_elements', 'do_shortcode' );to functions.php, if it is not there yet.
Update (2024): Since ACF 6.3 the [acf] shortcode is disabled by default on new installations. Enable it with add_action( 'acf/init', function () { acf_update_setting( 'enable_shortcode', true ); } );.
Sources: