Custom Shortcode Creation (Basic)

Est. Reading: 2 minutes
By: Rob LeVine
Created: 11/06/2022
Category:
Difficulty: Intermediate

Custom Shortcode Creation (Basic)

NOTE: The following is really not specific to Formidable, rather it's specific to WordPress, however, there are so many opportunities to use this in Formidable that I've written it as if it were a "Formidable thing".  Amusingly enough, when I got done with this, I discovered this entry in the Formidable Knowledgebase.

/* add_shortcode is a WordPress function and its first and second parameters can be anything you want, though you should make sure both are as unique as possible to avoid conflicts.  In the below example, I added 'ff_custom_' to minimize the chances of a conflict.  The second parameter must match exactly with the name of the function attached to the shortcode  */

add_shortcode('myCustomShortcode', 'ff_custom_doSomething');

/* In your PHP function, you'll do all the calculations, database searching or whatever and then use RETURN to send the information back to Formidable (or WordPress or whatever).  The data you return can be as simple as true/false or as "complex" as an entire stream of HTML.  Actually, you don't have to pass back any information (so just use return;) if you want the shortcode to do something rather than return something.

The parameter $atts is an array of attributes (parameters) you can pass to the function when calling it from a Formidable page or view, e.g., [myCustomShortcode entry=[id]].  In that example, there's a parameter named "entry" and its value is the value Formidable assigns to [id].

In this function, you can do whatever you can accomplish in PHP.  Frequently you pass in a Formidable entry id or key and then use the Formidable functions to get the information from that entry and do something with it.  That's what I'll do for the example below in which we return the square root of a number since we can't easily do square root using Formidable's math functions.  See this Formidable example.

*/

function ff_custom_doSomething($atts) {

  $entry_id = $atts["entry"];

  $number_field_id = 101; // example field id

  $val = FrmEntryMeta::get_entry_meta_by_field( $entry_id, $number_field_id, true );

  $myVal = sqrt($val );

  return $myVal;

}

In summary, you can have a shortcode almost anywhere you want, certainly without a page or view and the shortcode can do an infinite amount of things.

One comment on “Custom Shortcode Creation (Basic)”

Leave a Reply

Making the Best WordPress Plugin even better - Together

Take on bigger projects with confidence knowing you have access to an entire community of Formidable Experts and Professionals who have your back when the going gets tough. You got this!
Join the community
crosschevron-leftchevron-rightarrow-right