Friday, February 16, 2024
HomeMobile MarketingWordPress: Add A Shortcode To Show At the moment With Non-obligatory Formatting...

WordPress: Add A Shortcode To Show At the moment With Non-obligatory Formatting And Calculations


The ability to dynamically show content material permits WordPress customers to create extra participating, up-to-date, and related person experiences. One useful 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 in accordance with your WordPress settings or customized preferences. It’s much like one other shortcode I shared to calculate the variety of years since a particular date. This performance is not only a comfort; it’s a game-changer for websites needing to showcase well timed content material, similar to occasion notices, particular affords, or day by 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).

Use the At the moment Shortcode

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

Output

Feb 15, 2024, 12:11 PM

You possibly can customise this output by specifying a format. WordPress affords a variety of date and time formatting choices detailed at in our date article, which our shortcode absolutely helps. As an example:

Shortcode

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

If you happen to’d prefer to show the present time merely, you need to use:

Shortcode

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

Optionally, it’s also possible to embrace the time zone as nicely.

Shortcode

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

Output

February 15, 2024, 12:11 PM EST

Calculations from At the moment

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 doable:

Shortcode

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

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

WordPress Shortcode for At the moment with Non-obligatory 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 person supplied 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 just isn't empty
    if (!empty($atts['dateformat'])) {
        $formatted_output .= date($atts['dateformat'], $date);
    }

    // Format and append the time if the timeformat just isn't 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 just isn't 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 unwanted side 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 in accordance with 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, making certain consistency throughout your web site. This strategy leverages WordPress’s flexibility, permitting the shortcode to adapt to your chosen date and time configuration robotically.

Greatest Practices: Use in a Customized Plugin

Whereas including this code to your theme’s features.php file may be tempting, I’d strongly advocate putting it inside a customized plugin. This follow ensures that your shortcode stays purposeful and constant throughout theme adjustments, offering a extra secure and dependable person expertise.

Incorporating such customized shortcodes into your WordPress toolbox elevates your content material technique and underscores WordPress’s versatility and flexibility 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 inventive potentialities that WordPress affords.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments