How to Create a Custom Smart Tag

Overview

Would you like to create a custom Smart Tag to use inside your forms? If you’d like to provide, for example, a download link via a Smart Tag inside your email notification or a confirmation message, this can be easily done with a custom code snippet. In this tutorial, we’ll show you how to use PHP to create a custom Smart Tag.

Smart Tags offer a quick and easy way to pull specific information into a form field or notification email. WPForms comes with many built-in Smart Tags for you to use, and these can pull information like the current page’s URL or a logged-in user’s email address, etc.

With a little custom code added to your site, you can design a custom Smart Tag to pull even more useful information.

Setup

In the example below, we’re going to create a new custom Smart Tag to display a URL for a download link when our form is completed.

1) Adding the code

First, we’ll add the code to our site to create the Smart Tag and then process it as well so that we can use it inside our form builder.

/**
 * Register the Smart Tag so it will be available to select in the form builder.
 *
 * @link   https://wpforms.com/developers/how-to-create-a-custom-smart-tag/
 *
 */
function wpf_dev_register_smarttag( $tags ) {

	// Key is the tag, item is the tag name.
	$tags['download_link'] = 'Download Link';

	return $tags;
}
add_filter( 'wpforms_smart_tags', 'wpf_dev_register_smarttag' );

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

	// Only run if it is our desired tag.
	if ( 'download_link' === $tag ) {
		$link    = 'https://yoursite.com/file.pdf';
		// Replace the tag with our link.
		$content = str_replace( '{download_link}', $link, $content );
	}

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

Please remember to include both of the PHP functions as shown above.

The first function creates the Smart Tag and will require only basic name changes to be customized for any other Smart Tag.

The second function is where the bulk of the code will go. Inside of the if statement, you would need to add any code needed to pull the value(s) you’d like this Smart Tag to display.

2) Using the new custom Smart Tag

Once you’ve added the code snippets, edit any form and you can now see your custom Smart Tag(s) will be added to the bottom of the existing Smart Tag options list.

Your new custom Smart Tag will now displa

And that’s it! You’ve successfully created a new custom Smart Tag. Would you like to be able to process that custom Smart Tag inside an HTML / Code form field? If so, take a look at our article on How to Process Smart Tags in HTML Fields.

Filter References: