Introduction
WordPress shortcode on a page or post will be replaced with some content, and the process that happened in the background is as follows:
When WordPress “runs into” a shortcode it is instructed to look for a macro inside the brackets [ ], then the macro calls a callback function that will replace the shortcode with some dynamic content.
Enable shortcode everywhere
By default, WordPress ignores the shortcode if it finds it somewhere other than the part where the content of the post or page is entered. In order to activate shortcodes in other areas as well, it is necessary to add an appropriate filter to functions.php
Shortcode in widget
|
1 |
add_filter('widget_text', 'do_shortcode'); |
Now it is enough to put the shortcode in a regular Text widget and it in the area you want to display the content of the shortcode.
Shortcode in comments
|
1 |
add_filter( 'comment_text', 'do_shortcode' ); |
Shortcode in excerpt
|
1 |
add_filter( 'the_excerpt', 'do_shortcode'); |
Shortcode in topic header
If for some reason we want to insert a shortcode inside a template or plugin, e.g. “custom page template” we use the function do_shortcode( $content )
Example
At the place inside the code where we want the shortcode to appear, add the following code:
|
1 |
<?php echo do_shortcode("[shortcode_name]"); |
Example
If shortcode with opening and closing tag:
|
1 |
echo do_shortcode( '[shortcode_name]' . $text_to_be_wrapped_in_shortcode . '[/naziv_shortcode]' ); |
Example
To assign to a variable what the shortcode returns:
|
1 2 |
$var = do_shortcode( '' ); echo $var; |
Simple shortcode
Creating a shortcode
The procedure has the following flow:
- Create a callback function that will be called when eordpress “runs into” the shortcode
- Register the shortcode by giving it a unique name
- Hanging on the action hook
Callback function
This function does what shortcode is intended for, in the following example shortcode needs to “dump” the title of all posts written by the author “admin”:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function shortcode_lista_postova() { $args= array( 'author_name' => 'admin' ); $upit = new WP_Query( $args ); // The Loop $naslovi_postova = ''; if($upit->have_posts()) : while($upit->have_posts()) : $upit->the_post(); $naslovi_postova .='<a href="'.get_permalink().'">'.get_the_title().'</a><br>'; endwhile; wp_reset_query(); return $naslovi_postova; else: $nema_nista = '<p>Sorry, there are no post titles with your criteria.</p>'; return $nema_nista; endif; } |
NOTE:
The final “product” shortcode is text usually between HTML tags, to display it in the browser use return “string” and avoid the echo function. See more about this in the section of the article called “Printing HTML with a shortcode”.
Register shortcode
Registration is done with the function add_shortcode()
|
1 |
add_shortcode( $tag , $func ) |
- $tag – (string) (required) shortcode tag name inside brackets [ ]
- $func – (required) Callback function that is called when wordpress encounters a shortcode
|
1 2 3 |
function dodavanje_shortcode(){ add_shortcode('post_list', 'shortcode_lista_postova'); } |
Hanging on a hook
|
1 |
add_action( 'init', 'add_shortcode'); |
Calling shortcode
Now it is possible for the article author, whenever he needs to list all his posts, just insert the shortcode [post_list] in any part of the post or static page. This list will be updated dynamically thanks to the php code in the background.
Shortcode with parameters
Introduction
When “creating” a shortcode with parameters, the following functions are used:
- shortcode_atts() – wordpress function
- extract() – PHP function
shortcode_atts()
This function allows a sequence of parameter/default_value pairs to be used within a shortcode (ie between brackets [ ] ).
|
1 |
shortcode_atts( $pairs , $atts, $shortcode ) |
- $pairs – (required) array of pairs of type key/value (where value are default values)
- atts – (required) name of the variable under which the string inside the shortcode tag will be used
- $shortcode – (string) (optional) name of the shortcode that will be used
Example
|
1 2 3 4 5 6 7 8 |
$niz_za_shortcode = shortcode_atts( array( 'br_postova' => 1, 'pisac' => 'admin', ), $atts, 'post_list' ); |
In this example, the function creates an array of $atts pairs that is “linked” to the shortcode name in brackets [post_list]:
br_postova => 1
writer => ‘admin’
extract()
However the previously obtained string (key/value) must be “translated” into variables with associated default values.
The extract() function is used for this job. The variables are named $key and each has a default value associated with it. For shortcode purposes, this function is used in its simplest form and accepts only the string that needs to be changed as an attribute.
Example
If we assume that the string this function needs to process is the string from the previous example, then:
|
1 |
extract($niz_za_shortcode) |
After processing this function created (although it is not visible anywhere) an array of variables to which values were added, when printed the array would look like this:
$br_postova = 1
$writer = ‘admin’
Callback function
If I want the shortcode to display a certain number of article titles from a certain article writer.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
function shortcode_lista_postova($atts) { // creating variables and assigning default values extract( shortcode_atts( array( 'pisac' => 'admin', 'br_postova' => 1, ), $atts ) ); // Now I can use the variable $writer $num_posts $args= array( 'author_name' => $pisac, 'posts_per_page' => $br_postova, ); $upit = new WP_Query( $args ); // The Loop $naslovi_postova = ''; $naslovi_postova .='Izabrali ste da pogledate '.$br_postova. ' clanka od autora '.$pisac.':'.'</br>'; if($upit->have_posts()) : while($upit->have_posts()) : $upit->the_post(); $naslovi_postova .='<a href="'.get_permalink().'">'.get_the_title().'</a><br>'; endwhile; wp_reset_query(); return $naslovi_postova; else: $nema_nista = '<p>Zao nam je nema postova sa izbranim autorom '. $pisac.'</p>'; return $nema_nista; endif; } |
Registering and hooking is exactly the same as in the previous example:
|
1 2 3 4 |
function dodavanje_shortcode(){ add_shortcode('post_list', 'shortcode_lista_postova'); } add_action( 'init', 'add_shortcode'); |
Calling shortcode
Since we have defined default values, this code will work even without additional parameters, which means that the code will:
|
1 |
[spisak_postova] |
display one article (default value $br_posts=1) from the author of the article named ‘admin’ (default $writer is admin)
Now the user can select the article writer as well as the number of job titles to be displayed on one page:
|
1 |
[spisak_postova pisac="pera" br_postova="3"] |
Content in shortcode
If we want to insert the text before the list of articles from the previous examples, it is necessary to add a variable inside the callback function in the place where we want it to appear, but we also have to put it as a parameter that is passed to the function from the shortcode.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
function shortcode_lista_postova($atts, $content = null) { // creating variables and assigning default values extract( shortcode_atts( array( 'pisac' => 'admin', 'br_postova' => 1, ), $atts ) ); // Now I can use the variable $writer $num_posts $args= array( 'author_name' => $pisac, 'posts_per_page' => $br_postova, ); $upit = new WP_Query( $args ); // The Loop $naslovi_postova = ''; $naslovi_postova .= '<h2>'.$content.'</h2>'; $naslovi_postova .='Izabrali ste da pogledate '.$br_postova. ' clanka od autora '.$pisac.':'.'</br>'; if($upit->have_posts()) : while($upit->have_posts()) : $upit->the_post(); $naslovi_postova .='<a href="'.get_permalink().'">'.get_the_title().'</a><br>'; endwhile; wp_reset_query(); return $naslovi_postova; else: $nema_nista = '<p>Zao nam je nema postova sa izbranim autorom '. $pisac.'</p>'; return $nema_nista; endif; } |
Calling shortcode
The content that is passed through the shortcode is placed between the opening and closing tags of the shortcode as in the following example:
|
1 |
[list_of_posts]Content that we want to pass via shortcode[/list_of_posts] |
The result of this code is the same as in the previous examples, except that now above the list there is a typed text styled as an h2 title.
Print HTML with shortcode
Explanation of the problem
When the author of an article uses a shortcode, he usually expects the shortcode to return some text. The callback function gives that text to the browser as HTML. When writing a callback function, you should use the return string variable and avoid the echo function. Text printed with echo can appear where we didn’t plan, because it sends the text directly to the page regardless of the function it’s in. Echo prints as soon as php “comes”to it and doesn’t wait for the function it’s in to end, while return returns a string and terminates the function! It may be better understood with the following examples:
Example (echo)
|
1 2 3 4 5 |
function foobar_shortcode($atts) { echo "Foo"; // "Foo" is echoed to the page echo "Bar"; // "Bar" is echoed to the page } $var = foobar_shortcode() // $var has a value of NULL |
Example (return & echo)
|
1 2 3 4 5 |
function foobar_shortcode($atts) { return "Foo"; // "Foo" is returned, terminating the function echo "Bar"; // This line is never reached } $var = foobar_shortcode() // $var has a value of "Foo" |
Here is what they say about this on the official page:
“Note that the function called by the shortcode should never produce output of any kind. Shortcode functions should return the text that is to be used to replace the shortcode. Producing the output directly will lead to unexpected results.
Printing with return ‘string’
To gather all the HTML code that the shortcode should send to the browser, there are two approaches:
String concatenation
One way to “collapse” your HTML into a single variable is concatenation.
|
1 2 3 4 5 |
$naslovi_postova = ''; $naslovi_postova .= '<h2>'.$content.'</h2>'; $naslovi_postova .='Izabrali ste da pogledate '.$br_postova. ' clanka od autora '.$pisac.':'.'</br>' $naslovi_postova .='<a href="'.get_permalink().'">'.get_the_title().'</a><br>'; return $naslovi_postova; |
ob_start()
This function is used in conjunction with the supplementary function ob_get_clean(). From the moment it is placed in the code, it collects all the HTML code as well as everything that PHP prints with one of the functions for displaying on the screen. When it “runs into” the ob_get_clean() function in the code, it stops collecting and hands everything over to that function.
“Start remembering everything that would normally be outputted, but don’t quite do anything with it yet.”
Example
|
1 2 3 4 5 6 |
<?php ob_start(); // From this part, charging ?> is included Hello world, <a href="http://www.blogger.com/myotherpage.php">link</a> <h2><a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a></h2> <div class="style">Content</div> <?php $var = ob_get_clean(); // the filling of the buffer is interrupted, and the content is passed to the ob_get_clean() function, which then clears the buffer?> return $var |
The
$var variable that ended up saving the entire buffer now has a value:
|
1 2 3 |
Hello world, <a href="http://www.blogger.com/myotherpage.php">link</a> <h2><a href="sajt.com">Naslov</a></h2> <div class="style">Content</div> |
Example
This example is the same as in the section titled “Content in shortcode”, but instead of sting concatenation, the ob_start() and ob_get_clean() functions are used:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
function shortcode_lista_postova($atts, $content = null) { // creating variables and assigning default values extract( shortcode_atts( array( 'pisac' => 'admin', 'br_postova' => 1, ), $atts ) ); // Now I can use the variable $writer $num_posts $args= array( 'author_name' => $pisac, 'posts_per_page' => $br_postova, ); $upit = new WP_Query( $args ); // The Loop ob_start();?> <h2><?php echo $content ?></h2> <p>Izabrali ste da pogledate <?php echo $br_postova ?> clanka od autora <?php echo $pisac ?><p> <?php if($upit->have_posts()) : while($upit->have_posts()) : $upit->the_post();?> <h4><a href="<?php echo get_permalink()?>"> <?php echo get_the_title()?></a></h4> <?php endwhile; wp_reset_query(); return ob_get_clean(); else: $nema_nista = '<p>Zao nam je nema postova sa izbranim autorom '. $pisac.'</p>'; return $nema_nista; endif; } function dodavanje_shortcode(){ add_shortcode('post_list', 'shortcode_lista_postova'); } add_action( 'init', 'add_shortcode'); |
Hide discontinued shortcodes
In case the user changes the theme in which he used the shortcode, the new theme will not recognize them as a shortcode and will ignore them, i.e. it will treat them as plain text and print them as such. We can delete every “broken” shortcode:
- manual i.e. to open every post where the shortcode was used and delete it.
- by adding code to functions.php of the new theme:
1add_shortcode( 'shortcode_tag', '__return_false' );
at the ‘shortcode_tag’ place, you should insert the name of each individual shortcode that you want to remove
