Enabling Shortcodes in Divi Module Fields

|

The Divi Theme's many modules include a variety of fields in which you can enter URLs and text to be displayed by the modules. In many cases, however, these are limited to the static text you type into the modules' settings. What if you want to use be able to dynamically generate the URLs / text using shortcodes, e.g. a URL collected using the Advanced Custom Fields (ACF) plugin? Here's how to do it.

Enable Shortcodes using Divi Shortcode Enabler

Divi Shortcode Enabler is a plugin which adds support for shortcodes in places where Divi does not normally execute them, for example in various Divi module fields.

It adds support for shortcodes in the following module fields:

    • Accordion Module
      • Title
    • Bar Counter Module
      • Percent
    • Blurb Module
      • Title
      • Image
      • URL
      • Alt
    • Button Module
      • Button Text 
      • Button URL
    • Call To Action (CTA) Module
      • Title
      • Button Text
      • Button URL
    • Circle Counter Module
      • Title
      • Number
    • Columns
      • Column Link URL
    • Contact Form Module
      • Email
      • Redirect URL
      • Success Message
      • Message Pattern
      • Field Titles (Placeholder)
    • Fullwidth Header Module
      • Title
      • Subheading Text
      • Button #1 Link Text
      • Button #2 Link Text
      • Button #1 Link URL
      • Button #2 Link URL
    • Fullwidth Image Module
      • Image URL
      • Title Text
      • Alt
  • Image Module
    • Image URL
    • Link URL
    • Title Text
    • Alt
  • Number Counter Module
    • Title
    • Number
  • Pricing Table Module
    • Title
    • Subtitle
    • Currency
    • Sum
    • Frequency
    • Button Text
    • Button URL
  • Rows
    • Row Link URL
  • Slider Module Slides
    • Title
    • Button Text
    • Button URL
    • Title Text
    • Alt
  • Social Media Follow Module
    • Account Link URL
  • Tab Module
    • Title
  • Toggle Module
    • Title
  • All Modules, Rows and Sections
    • Background Image URL
    • Module Link URL
    • CSS ID
    • CSS Class
  • Third-Party Plugins

Enable Shortcodes via PHP

The following PHP code (taken from my Divi Shortcode Enabler plugin) will search the page / post content for various module fields, and process any shortcodes contained within them.

if (!class_exists('DBDSE_EnableShortcodesInModuleFields')) {
	class DBDSE_EnableShortcodesInModuleFields {

		static public function supportedFields() {
			return apply_filters(
				'dbdsp_fields_to_process', 
				array(
					'et_pb_accordion_item' => array('title'),
					'et_pb_blurb' => array('title', 'url', 'image', 'alt'),
					'et_pb_button' => array('button_url', 'button_text'),
					'et_pb_circle_counter' => array('title', 'number'),
					'et_pb_cta' => array('title', 'button_text', 'button_url'),
					'et_pb_image' => array('url', 'src', 'title_text', 'alt'),
					'et_pb_number_counter' => array('title', 'number'),
					'et_pb_counter' => array('percent'), 
					'et_pb_pricing_table' => array('title', 'subtitle', 'currency', 'sum', 'button_text', 'button_url'),
					'et_pb_tab' => array('title'),
					'et_pb_slide' => array('heading', 'button_text', 'button_link', 'image_alt', 'title_text'),
					'db_pb_slide' => array('button_text_2', 'button_link_2'), // Divi Booster added second slide buttons
					'et_pb_fullwidth_header' => array('title', 'subhead', 'button_one_text', 'button_two_text', 'button_one_url', 'button_two_url'),
					'et_pb_fullwidth_image' => array('src', 'title_text', 'alt'),
					'et_pb_contact_field' => array('field_title')
				)
			);
		}
		
		public function init() {
			add_filter('the_content', array($this, 'processShortcodes')); // Standard content
			add_filter('et_builder_render_layout', array($this, 'processShortcodes')); // Theme builder layout content
			add_filter('dbdse_et_pb_layout_content', array($this, 'processShortcodes')); // Global module content
			add_filter('et_pb_module_shortcode_attributes', array($this, 'preventShortcodeEncodingInModuleSettings'), 11, 3);
		}

		public function processShortcodes($content) {
			$modules = self::supportedFields();
			do_action('dbdsp_pre_shortcode_processing');
			foreach((array) self::supportedFields() as $module=>$fields) {
				foreach($fields as $field) {
					$regex = '#['.preg_quote($module).' [^]]*?\b'.preg_quote($field).'="([^"]+)"#';
					$content = preg_replace_callback($regex, array($this, 'processMatchedAttribute'), $content);
				}
			}
			do_action('dbdsp_post_shortcode_processing');
			return $content;
		}

		protected function processMatchedAttribute($matches) {
			
			// Exit if not properly matched
			if (!is_array($matches) || !isset($matches[0])) { return ''; } 
			if (!isset($matches[1])) { return $matches[0]; }
			
			// Define character replacements
			$encoded = array('%'.'22', '%'.'91', '%'.'93');
			$decoded = array('"', '[', ']');
				
			// Get the decoded parameter value
			$val = $matches[1];
			$val = str_replace($encoded, $decoded, $val); // decode encoded characters
			$val = do_shortcode($val);
			$val = str_replace($decoded, $encoded, $val); // re-encode

			// Return the replacement value
			$result = str_replace($matches[1], $val, $matches[0]);

			return $result;
		}
		
		public function preventShortcodeEncodingInModuleSettings($props, $attrs, $render_slug) {
  			if (!is_array($props)) { return $props; }
			if (!empty($_GET['et_fb'])) {
				if ($render_slug === 'et_pb_image' && !empty($attrs['url']) && strpos($attrs['url'], '[') !== false && strpos($attrs['url'], ']') !== false) { 
					$props['url'] = $attrs['url'];
					$props['url'] = str_replace(array('[', ']', '"'), array('[', ']', '"'), $props['url']);
				}
			}
			return $props;	
		}
	}
	(new DBDSE_EnableShortcodesInModuleFields)->init();
}

/* Add global modules filter */
add_filter('the_posts', 'dbdse_filter_global_modules');

function dbdse_filter_global_modules($posts) {
	if (!dbdse_is_frontend() || empty($posts) || count($posts)!==1 || empty($posts[0]->post_type) || empty($posts[0]->post_content)) { 
		return $posts; 
	} 
	if ($posts[0]->post_type === 'et_pb_layout') {
		$posts[0]->post_content = apply_filters('dbdse_et_pb_layout_content', $posts[0]->post_content);
	}
	return $posts;
}

function dbdse_is_frontend() {
	return (!is_admin() && !isset($_GET['et_fb']));
}

This post may contain referral links which may earn a commission for this site

Divi Booster

Hundreds of new features for Divi
in one easy-to-use plugin

67 Comments

  1. That seems to be exactly what I'm looking for : passing down a url parameter to a link.

    I've tried it, but it doesn't seem to work. I can see two reasons :
    – I'm using Divi Builder, not Divi Theme (I put the code in the plugin's functions.php file though, so it shouldn't be it).
    – It's a price table button, so maybe the code is different in some way ?

    Some help would be greatly appreciated :) I understand the big picture of how that works, but it's a bit above my level !

    Reply
    • Hey Laurent, yeah different code is needed for the pricing table button. I've just done a big update of the code (and implemented it as a plugin), so it should now support shortcodes in pricing table buttons. Hope it helps!

      Reply
  2. I want to say Thanks for the code, But I need to point out that it did not work correctly for me right off the bat.

    The issue I encountered was that the regex pattern for et_pb_image looks for url= when it should be src=.

    Reply
    • Hey Weeezl, thanks for the feedback. The image module actually supports both the "src" and the "url" parameters. "src" is the URL of the image being displayed, while "url" is the (optional) link to which clicking on the image will take you. My code was targeted at the latter of these, but you modification should work for the former (as you found).

      Reply
      • what about et_pb_blurb? how do you make this work for that url/link.. I tried '#\[et_pb_blurb [^\]]*? url="([^"]+)"#', BUT, alas, didn't work.

        Reply
        • I'd have thought that would have worked for you… I've just updated the code, both in the post above and in my new Divi Shortcode Enabler plugin, to handle blurb module titles, images and modules. Hope it helps, but let me know if you still can't get it going. Cheers!

          Reply
  3. Hi!
    I am a newbie in DIV, php and CSS.
    I want to logout without a confirmation, done by a button.
    I found a code (starting with "add_action('check_admin_referer', 'logout_without_confirm', 10, 2);…"), which I have added to my child functions.php).
    How can I now call this function with the DIVI-button?
    I have tried several variants out, but it didnt succeed.
    Thanks in advance for your help!

    Reply
    • Hey Martin, you can create a link that performs the logout (and combines well with the "logout without confirmation" code you found). I've just put up a post on how to do it:

      Creating a Logout Button in Divi

      I hope that helps, but let me know if you still can't get it to work. Thanks!

      Reply
  4. Hi Dan,

    Thanks for the tip! If I wanted to use a shortcode in the 'title' of a 'Blurb module' in divi, how should I change the code to reflect this?

    Also, is it possible to use shortcode in the URL of an 'Image module' as well? I cannot seem to get this working either.

    Thanks in advance,
    Karl.

    Reply
    • Hey Karl, sorry I'm only just managing to reply to this now. I've updated the code so that it should handle both the title of the blurb module and the image module URL. You can now get the code as a (currently free) plugin – Divi Shortcode Enabler. You may find that easier to get working that the PHP code.

      Reply
  5. Hi Dan – Thank you for this post/code.

    Does it work with the current version of Divi Builder? I can't get it to work in the divi button module. The URL produced is http://%91field%20lat%93.com.

    Any trick to get this to work? It's installed in the child functions.php file.

    Thanks you,
    Sean

    Reply
    • Hey Sean, sorry I'm only just getting back to you. I've updated the code to have better shortcode matching which I think should sort this out for you. Let me know if you still can't get it to work. Thanks!

      Reply
  6. Hi there , just inserted your code in the function.php of my child theme , inserted the my shortcode in the url field of the button but it doesn't seem to work?
    the shortchode i insert is still interpreted as an url when i click on the divi button. when i check the url field afterwards , my shorcode is modified and has some kind of url like look. any clue? thanks a lot.

    Reply
    • Hi Vincenet, I've improved the code with better shortcode detection which I think would probably solve this issue if you're still having it. Thanks!

      Reply
  7. Have you got an idea how to put an ACF shortcode in title field of tabs module ?
    Right now, when I try, I see the shortcode on front end instead of the simple text entered in the custom field.
    I believe it's kind of the same type of code you provided but I would really appreciate if you could do the same thing with title fields in different DIVI modules like tabs module, call to action module, accordions etc…

    Thx in advance

    Reply
    • Hi Charlotte, I've updated the code so it should now handle ACF shortcodes in the tab module title field. I've also added support for shortcodes in CTA and accordion modules. Sorry I wasn't able to answer this sooner, but I hope it is still useful!

      Reply
  8. Hmmm … does not work for me, where do I have to insert this code exactly?

    Reply
    • Hey Tobias, the code would ideally be added into the functions.php file of a child theme (at the end of the file is fine). It could also be added directly into Divi's own functions.php file, but this will be overwritten when Divi is updated so I'd only use it for testing. Note that when adding code to a PHP file you need to pay attentions to the PHP start / end tags. This post has a bit more info:

      https://divibooster.com/adding-php-code-to-the-divi-theme/

      I hope that helps, but let me know if you still can't get it to work. Cheers!

      Reply
    • Hey Tobias.. I bit late for this reply, yet it may help someone else. To make things easy, I use the free Custom Functions plugin. And this function works perfectly once copied and paste into the plugin PHP insert area. Dan is an amazing guy for posted this valuable info.

      Reply
  9. Totally AWESOME! Thank you so much!

    Reply
  10. Actually, never mind, I got it. :) Just replaced button_url with button_text in your code. Thanks!!

    Reply
    • Nice one, JDar :)

      Reply
    • JDar, did you find how to do it with tabs title? I've been on this since an hour but I can't seem to figure it out.
      I really needs this feature to work.
      Thx

      Reply
      • Hi Charlotte, if you're still looking to do this I've just updated the code to handle shortcodes in tab titles. I've also released the code as a (currently free) plugin – Divi Shortcode Enabler.

        Reply
  11. This is great. I'd like to insert a shortcode into the button title and/or tab titles, rather than the URL. Any tips on how to accomplish that?

    Reply
  12. It works perfect on new Divi Version!
    Thanks for the code ;)

    Reply

Submit a Comment

Comments are manually moderated and approved at the time they are answered. A preview is shown while pending but may disappear if your are cookies cleared - don't worry though, the comment is still in the queue.

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