Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

WordPress: Add a Shortcode To Display Today With Optional Formatting and Calculations

The power to dynamically display content allows Wordpress users to create more engaging, up-to-date, and relevant user experiences. One handy application of this dynamic capability is using shortcodes to insert custom content into posts, pages, and widgets.

This article introduces a custom shortcode to display the current date and time and even calculate date adjustments, all formatted according to your WordPress settings or custom preferences. It’s similar to another shortcode I shared to calculate the number of years since a specific date. This functionality is not just a convenience; it’s a game-changer for sites needing to showcase timely content, such as event notices, special offers, or daily messages.

The today shortcode displays today’s date, time, and even time zone with the added flexibility of formatting the output date and time and calculating date differences—all of which are displayed dynamically every time a page is loaded (as long as it’s not cached, of course).

How to Use the Today Shortcode

Once set up, using the shortcode is straightforward. It will default display the current date and time based on your WordPress settings. For example:

Shortcode

[today]

Output

Feb 15, 2024, 9:58 AM

You can customize this output by specifying a format. WordPress offers a wide range of date and time formatting options detailed at in our date article, which our shortcode fully supports. For instance:

Shortcode

[today dateformat="F j, Y" timeformat="g:i A"]

Output

February 15, 2024

If you’d like to display the current time simply, you can use:

Shortcode

[today dateformat="" timeformat="g:i A"]

Output

9:58 AM

Optionally, you can also include the time zone as well.

Shortcode

[today dateformat="F j, Y" timeformat="g:i A" zoneformat="T"]

Output

February 15, 2024, 9:58 AM EST

Calculations from Today

Moreover, the shortcode supports calculations to add or subtract days, weeks, months, or years from the current date:

Shortcode

[today calculate="+1 month" dateformat="F j, Y" timeformat=""]

Output

March 15, 2024

Time calculations are also possible:

Shortcode

[today calculate="+2 hours" dateformat="" timeformat="g:i A"]

Output

11:58 AM

The shortcode offers a powerful tool for WordPress site owners, enabling dynamic content display that can significantly enhance user engagement and content relevance. Following the guidelines and examples, you can leverage this shortcode to its full potential, ensuring your site remains fresh, accurate, and timely.

WordPress Shortcode for Today with Optional Calculations and Formatting

function calculate_today_shortcode( $atts ) {
    // Fetch the WordPress-configured date and time formats as defaults
    $default_date_format = get_option('date_format', 'F j, Y');
    $default_time_format = get_option('time_format', 'g:i A');

    // Fetch and set the WordPress-configured time zone
    $timezone_string = get_option('timezone_string');
    if (empty($timezone_string)) {
        $offset = get_option('gmt_offset');
        $timezone_string = timezone_name_from_abbr('', $offset * 3600, false);
    }
    date_default_timezone_set($timezone_string);

    // Set default attributes and merge with user provided ones
    $atts = shortcode_atts(
        array(
            'dateformat' => $default_date_format, // Default date format
            'timeformat' => $default_time_format, // Default time format
            'calculate' => '', // No date calculation by default
            'zoneformat' => '', // Default zone format is blank
        ),
        $atts,
        'today'
    );

    // Calculate the date if needed
    $date = $atts['calculate'] ? strtotime($atts['calculate']) : time();

    // Initialize an empty string for the formatted output
    $formatted_output = '';

    // Format and append the date if the dateformat is not empty
    if (!empty($atts['dateformat'])) {
        $formatted_output .= date($atts['dateformat'], $date);
    }

    // Format and append the time if the timeformat is not empty
    if (!empty($atts['timeformat'])) {
        // Add a separator if both date and time are being displayed
        if (!empty($formatted_output)) {
            $formatted_output .= ', ';
        }
        $formatted_output .= date($atts['timeformat'], $date);
    }

    // Append the time zone if zoneformat is not empty
    if (!empty($atts['zoneformat'])) {
        // Add a separator if date/time and zone are being displayed
        if (!empty($formatted_output)) {
            $formatted_output .= ' ';
        }
        // Use 'e' for the timezone identifier, 'T' for the timezone abbreviation,
        // or any other format supported in the PHP date function
        $formatted_output .= date($atts['zoneformat'], $date);
    }

    // Reset to the default timezone to avoid side effects
    date_default_timezone_set('UTC');
    
    return $formatted_output;
}
add_shortcode( 'today', 'calculate_today_shortcode' );

The magic behind the today shortcode lies in its PHP function, which utilizes WordPress’s add_shortcode function. This function fetches the current date and time, applies any user-defined calculations, and formats the output according to either the WordPress settings or the custom format specified in the shortcode. Dynamically adjusting to the WordPress-configured time zone ensures accuracy and relevance for all users, regardless of their geographic location.

We also emphasize the importance of setting the default format to match WordPress settings, ensuring consistency across your site. This approach leverages WordPress’s flexibility, allowing the shortcode to adapt to your chosen date and time configuration automatically.

Best Practices: Use in a Custom Plugin

While adding this code to your theme’s functions.php file might be tempting, I’d strongly recommend placing it within a custom plugin. This practice ensures that your shortcode remains functional and consistent across theme changes, providing a more stable and reliable user experience.

Incorporating such custom shortcodes into your WordPress toolbox elevates your content strategy and underscores WordPress’s versatility and adaptability as a content management system. Whether you’re a blogger, marketer, or event organizer, the today shortcode is a testament to the creative possibilities that WordPress offers.

©2024 DK New Media, LLC, All rights reserved.

Originally Published on Martech Zone: WordPress: Add a Shortcode To Display Today With Optional Formatting and Calculations



This post first appeared on How To Optimize Prestashop For Increased SEO And Conversions, please read the originial post: here

Share the post

WordPress: Add a Shortcode To Display Today With Optional Formatting and Calculations

×

Subscribe to How To Optimize Prestashop For Increased Seo And Conversions

Get updates delivered right to your inbox!

Thank you for your subscription

×