Dynamically populate time based select fields in WordPress metaboxes

If you’ve got more than one time based select field in a PHP form, it makes sense to create a reusable function to prep those iterations for you instead of manually constructing an array. And, because you’re going to be using different identifiers for the different fields, you’ll want to just construct a top level array that you can step through independently for each of your select fields. Thanks to a post on StackOverflow, we can easily create that top level array, and then implement it into our fields.

I’m developing using an MVC architecture, so I include this function at the top of the specific view I need it in:

format( $format );
    }
    return $times;
}
$fullday = hoursRange( 0, 86400, 60 * 30, 'h:i a' );
?>

 

Then, at each select field, I iterate through the array with the specific values I need for that field:

  •  

    You can adjust the formatting, or restrict the range as needed.