Friday, February 16, 2024
HomeMobile MarketingWordPress: Add A Shortcode To Show At present With Optionally available Formatting...

WordPress: Add A Shortcode To Show At present With Optionally available Formatting And Calculations


The ability to dynamically show content material permits WordPress customers to create extra partaking, up-to-date, and related consumer experiences. One helpful software of this dynamic functionality is utilizing shortcodes to insert customized content material into posts, pages, and widgets.

This text introduces a customized shortcode to show the present date and time and even calculate date changes, all formatted based on your WordPress settings or customized preferences. It’s just like one other shortcode I shared to calculate the variety of years since a selected date. This performance isn’t just a comfort; it’s a game-changer for websites needing to showcase well timed content material, comparable to occasion notices, particular gives, or each day messages.

The at the moment shortcode shows at the moment’s date, time, and even time zone with the added flexibility of formatting the output date and time and calculating date variations—all of that are displayed dynamically each time a web page is loaded (so long as it’s not cached, after all).

Learn how to Use the At present Shortcode

As soon as arrange, utilizing the shortcode is simple. It should default show the present date and time based mostly in your WordPress settings. For instance:

Output

Feb 15, 2024, 12:11 PM

You’ll be able to customise this output by specifying a format. WordPress gives a variety of date and time formatting choices detailed at in our date article, which our shortcode absolutely helps. For example:

Shortcode

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

When you’d wish to show the present time merely, you should use:

Shortcode

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

Optionally, you can even embrace the time zone as properly.

Shortcode

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

Output

February 15, 2024, 12:11 PM EST

Calculations from At present

Furthermore, the shortcode helps calculations so as to add or subtract days, weeks, months, or years from the present date:

Shortcode

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

Time calculations are additionally potential:

Shortcode

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

The shortcode gives a strong software for WordPress web site house owners, enabling dynamic content material show that may considerably improve consumer engagement and content material relevance. Following the rules and examples, you possibly can leverage this shortcode to its full potential, guaranteeing your web site stays recent, correct, and well timed.

WordPress Shortcode for At present with Optionally available Calculations and Formatting

perform calculate_today_shortcode( $atts ) {
    // Fetch the WordPress-configured date and time codecs 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 consumer offered 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 clean
        ),
        $atts,
        'at the moment'
    );

    // Calculate the date if wanted
    $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 just not empty
    if (!empty($atts['dateformat'])) {
        $formatted_output .= date($atts['dateformat'], $date);
    }

    // Format and append the time if the timeformat is just not empty
    if (!empty($atts['timeformat'])) {
        // Add a separator if each 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 just 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 every other format supported within the PHP date perform
        $formatted_output .= date($atts['zoneformat'], $date);
    }

    // Reset to the default timezone to keep away from unintended effects
    date_default_timezone_set('UTC');
    
    return $formatted_output;
}
add_shortcode( 'at the moment', 'calculate_today_shortcode' );

The magic behind the at the moment shortcode lies in its PHP perform, which makes use of WordPress’s add_shortcode perform. This perform fetches the present date and time, applies any user-defined calculations, and codecs the output based on both the WordPress settings or the customized format specified within the shortcode. Dynamically adjusting to the WordPress-configured time zone ensures accuracy and relevance for all customers, no matter their geographic location.

We additionally emphasize the significance of setting the default format to match WordPress settings, guaranteeing consistency throughout your web site. This strategy leverages WordPress’s flexibility, permitting the shortcode to adapt to your chosen date and time configuration routinely.

Finest Practices: Use in a Customized Plugin

Whereas including this code to your theme’s features.php file is perhaps tempting, I’d strongly suggest inserting it inside a customized plugin. This apply ensures that your shortcode stays purposeful and constant throughout theme adjustments, offering a extra secure and dependable consumer expertise.

Incorporating such customized shortcodes into your WordPress toolbox elevates your content material technique and underscores WordPress’s versatility and adaptableness as a content material administration system. Whether or not you’re a blogger, marketer, or occasion organizer, the at the moment shortcode is a testomony to the artistic potentialities that WordPress gives.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments