executing shortcode inside the_excerpt() in WordPress

in PHP/Tutorials & Samples/Wordpress

I recently had a project that required me to use WordPress shortcode inside a WordPress excerpt. Anybody who is familiar with WordPress will tell you that: WordPress does not allow you to use shortcode in excerpts!
Wordpress allows you to use shortcodes for anything called through the_content() function, but the shortcode will be displayed as-is when the same post is called through the_excerpt() function.

According to the WordPress Codex, no code or html tags are executed in the_excerpt() function.
Well, it turns out that this is just the default behaviour of WordPress. If you wish to allow excerpts to execute shortcodes, you can simply modify functions.php in your theme by adding the following line of code:

add_filter( 'the_excerpt', 'shortcode_unautop');
add_filter( 'the_excerpt', 'do_shortcode');

Once this line of code is added, your shortcodes will now be executed inside the_excerpt(). The first line tells WordPress to not automatically add paragraphs, known as the autop filter. This is the filter that turns your line breaks into paragraphs and break tags in WordPress. shortcode_unautop turns off this functionality. ( so, if your shortcode is on its own line, it will not get wrapped in a paragraph tag. The second line tells WordPress that it should process shortcodes for excerpts.

Now, in theory, this is all you need to make shortcodes work with excerpts. But many people will still have isssues making shortcodes work with excerpts, depending on the plugin that they are using. Certain plugins have additional hooks inside the footer.php file. Some of these plugins will NOT work, even with the code above added to the functions.php file. A case of these plugins is the WPAudioPlayer Plugin

Tags:

Mifty Yusuf is a Montreal-based software developer who enjoys playing with new web technologies as well as comic books and illustrations. He beleives that, no matter what the question is, the answer is always Batman!

2 Comments

Leave a Reply

Your email address will not be published.

*

Latest from PHP

Go to Top