Dynamic Opening Hours WordPress woman opening store

Dynamic Opening Hours in WordPress

Dynamic Opening Hours WordPress woman opening store

Today we were asked to create a simple dynamic opening hours script to display the closing time of a store based on the current day of the week. The concept is really simple but we couldn’t find an example of someone having done this before.

All we need to do is get the day of the week from the PHP DateTime object which returns an integer which we’ll use to reference an array of closing time statements. Our array starts on Sunday – where the store is closed and ends with Saturday, closing at 12pm.

We’ve added two short strings $start_span and $close_span, the first opening a span tag with the class “top-header-hours” and an icon tag to add a Font Awesome clock-o icon. The span class allows us to add any required CSS. The second string simply closes the span tag.

That’s all we need. You’ll see that the whole thing is added by a shortcode and that is added to the functions.php file in our child-theme. Many theme options will allow you to add the shortcode [dynamic_opening_hours] straight into where we add content to the top of the header. If that doesn’t work create a copy of your header.php file in your child-theme and add the code inside the function in there.

 

<?php

function get_hours(){
    $dayofweek = date('w', strtotime($date));
    $days = array('Closed today','Open until 7pm today','Open until 6pm today','Open until 7pm today','Open until 6pm today','Open until 7pm today','Open until 12pm today');
    $todays_hours = $days[$dayofweek];
    $start_span = '<span class="top-header-hours"><i class="fa fa-clock-o"></i>';
    $end_span ='</span>';
    return $start_span.$todays_hours.$end_span;
}
add_shortcode( 'dynamic_opening_hours', 'get_hours' );

?>

This is the CSS you’ll want to add to make your icon work.

.fa {
    display: inline-block;
    font: normal normal normal 14px/1 FontAwesome;
    font-size: inherit;
    text-rendering: auto;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.fa-envelope-o:before {
    content: "\f003";
}