Skip to main content
All CollectionsDynamic ShortcodesFor Developers
Add a simple Dynamic Shortcode written in PHP
Add a simple Dynamic Shortcode written in PHP
Updated over 2 months ago

For adding simple custom Dynamic Shortcodes written in PHP we provide an easy to use interface similar to the one for adding WordPress Shortcodes.


โ€‹Note: This is a simplified interface that does not have all the features of the canonical interface. If you want to extend the plugin and add complex Dynamic Shortcodes you should probably use that.

Example

The following will add the simple shortcode that is given a name as the first argument and the result is a greeting for that name, {greet:Jane} will expand to "Hello Jane!".

Note: This serves only as an example. This same custom Shortcode could be created much more easily with Power Shortcodes and without the need to write any PHP.

function greeter_dynamic_shortcode( $args, $keyargs, $type ) {
return "Hello $args[0]!";
}

add_action ( 'dynamic-shortcodes/types/register', function( $dsh_manager ) {
$dsh_manager->register_callback( 'greet', 'greeter_dynamic_shortcode' );
});

To register a Dynamic Shortcode you use the register_callback method of the Shortcodes manager. You can get the manager with the dynamic-shortcodes/types/register action.

The register_callback method is given a name and a callback. Then every time a Dynamic Shortcode with the name is encountered the given callback is called. When called the callback will receive an array of args ($args), an array of keyargs ($keyargs), and the Shortcode name ( parameter $type, in our case the value will be 'greet').

Advantages over custom WordPress Shortcodes

  • If you want to pass arguments to the Shortcodes Dynamic Shortcodes are much easier to write. Compare [greet name="Jane"] with {greet:Jane}

  • You can use filters: {greet:Jane|strtolower}

  • You can use the fallback {greet:Jane?fallback}

  • WordPress Shortcode always return strings. While Dynamic Shortcodes can return any kind of value. This is useful when used in combination with other Dynamic Shortcodes.

Did this answer your question?