How to Create a Smart Tag for the Current Time

Overview

Have you ever wanted to create a custom Smart Tag for the time? There is already a Smart Tag for the Date but did you know you can create one for the Current Time as well? With a small PHP snippet, you can easily achieve this and we’ll show you how!

Setup

In the code snippet below, you’ll see there are two functions. One will create the Smart Tag and the other will provide the ability to add the new Smart Tag to the list in the form builder.

Simply add this code to your site.

/**
 * Create a custom Smart Tag 
 *
 * @link https://wpforms.com/developers/how-to-create-a-smart-tag-for-the-current-time
 *
 */
function wpf_dev_register_smarttag( $tags ) {
	// Key is the tag, item is the tag name.
	$tags['current_time'] = 'Current Time';
	return $tags;
}
add_filter( 'wpforms_smart_tags', 'wpf_dev_register_smarttag' );

/**
 * Process the Smart Tag.
 *
 * @link https://wpforms.com/developers/how-to-create-a-smart-tag-for-the-current-time
 *
 */
function wpf_dev_process_smarttag( $content, $tag ) {

	// Only run if it is our desired tag.
	if ( 'current_time' === $tag ) {
		date_default_timezone_set('US/Eastern');
		$link    = date('h:i A');
		// Replace the tag with our link.
		$content = str_replace( '{current_time}', $link, $content );
	}

	return $content;
}
add_filter( 'wpforms_smart_tag_process', 'wpf_dev_process_smarttag', 10, 2 );

And after saving the code, you’ll now be able to use this new custom Smart Tag in your form builder.

Once the code has been added to your site, a Current Time Smart Tag can be used in your form builder

And that’s it! You’ve now created a new Smart Tag for the Current Time. Would you like to process Smart Tags inside field labels? Take a look at our tutorial on How to Process Smart Tags in Field Labels.