Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a closing shortcode to Wordpress template file?

Okay, so you can add shortcodes to WP template files like:

<?php echo do_shortcode('[my_awesome_shortcode]'); ?>

but what if the shortcode is intended to wrap around content like this:

[my_awesome_shortcode]
Hey, this is the content within the awesome shortcode.
[/my_awesome_shortcode]

I'm a bit unsure how to put that into a template file.

like image 385
Ian Avatar asked Dec 01 '22 21:12

Ian


2 Answers

The solution that worked for me was to combine shortcodes into a single string, so

<?php echo do_shortcode('[my_awesome_shortcode]<h1>Hello world</h1>[/my_awesome_shortcode]'); ?>

will work!

If you have a long chain of shortcode commands you want to execute, create a separate string for them like this

$shortcodes = '[row]';
    $shortcodes .= '[column width="2/3"]';
        $shortcodes .= 'Content';
    $shortcodes .= '[/column]';
    $shortcodes .= '[column width="1/3"]';
        $shortcodes .= 'More Content';
    $shortcodes .= '[/column]';
$shortcodes .= '[/row]';

Then execute the entire thing like this

<?php echo do_shortcode($shortcodes); ?>
like image 158
internet-nico Avatar answered Dec 22 '22 07:12

internet-nico


According to http://codex.wordpress.org/Shortcode_API#Enclosing_vs_self-closing_shortcodes

adding $content = null to the shortcut function should do the trick:

function my_awesome_shortcode_func( $atts, $content = null ) {
   return '<awesomeness>' . $content . '</awesomeness>';
}

add_shortcode( 'my_awesome_shortcode', 'my_awesome_shortcode_func' );

so that:

[my_awesome_shortcode]
Hey, this is the content within the awesome shortcode.
[/my_awesome_shortcode]

would result in:

<awesomeness>Hey, this is the content within the awesome shortcode.</awesomeness>
like image 27
mgherkins Avatar answered Dec 22 '22 07:12

mgherkins