Shortcode If/Then Based on Dates

Hello! I know, it’s been a long time since I’ve posted – and I don’t even have a good excuse to give you. Honestly I just haven’t been motivated to post anything, but that’s all changed today.

The other day I stumbled upon custom shortcode that allows you to have a simple IF-THEN block, so I decided to modify it to use a date range for the condition. Here it is:

/* To use the IF shortcode:
 *  [if lowerdate="2022-11-25 07:00:00" upperdate="2022-11-25 09:00:00"]
 *   shortcode or text if true goes here
 *  [else]
 *   shortcode or text if false goes here
 *  [/if]
 */
function if_statement($atts, $content) {
    if (empty($atts)) return '';
    $a = shortcode_atts( array(
        'lowerdate' => '2022-11-24 08:00:00',
        'upperdate' => '2022-11-26 08:00:00',
    ), $atts);
    
    // Validate lowerdate and upperdate
    
    if (DateTime::createFromFormat('Y-m-d H:i:s', $a['lowerdate']) == false) return '';
    if (DateTime::createFromFormat('Y-m-d H:i:s', $a['upperdate']) == false) return '';
    
    $tzstring = get_option( 'timezone_string' );
    $currentDate = current_datetime();
    
    $lowerDate = new DateTime($a['lowerdate'], new DateTimeZone($tzstring));
    $upperDate = new DateTime($a['upperdate'], new DateTimeZone($tzstring));
    
    if (($currentDate > $lowerDate) && ($currentDate < $upperDate)){
        $condition = true;
    } else {
        $condition = false;
    } 

    $else = '[else]';
    if (strpos($content, $else) !== false) {
        list($if, $else) = explode($else, $content, 2);
    } else {
        $if = $content;
        $else = "";
    }

    return do_shortcode($condition ? $if : $else);
}

// register shortcode
add_shortcode('if', 'if_statement');

It’s pretty simple to use. Just create a new shortcode block like this:

[if lowerdate="2022-11-26 07:00:00" upperdate="2022-11-27 07:00:00"]
  Do this if the current date is between lowerdate and upperdate
[else]
  Do something else if it's not in the range
[/if]

You can also execute shortcode inside the if block We use the Woo Discount Rules plugin, so it’s nice to only show a sale when it’s running.

[if lowerdate="2022-11-26 00:00:00" upperdate="2022-11-26 08:00:00"]
  [awdr_sale_items_list columns="4" per_page="4"]
[/if]

I hope this is helpful. Thanks for visiting!

Leave a Reply

Your email address will not be published. Required fields are marked *