Shortcodes are one of the most powerful tools the team behind WordPress have added, and it is especially useful for inserting reusable content into pages and posts. It has been widely used since it was introduced and most modern themes and plugins have shortcodes included to make their use more flexible. Some plugins are complete packages of useful functions made available as shortcodes – check this collection to see yourself. They can be placed anywhere from post, pages and even widgets if enabled.

Shortcodes are powerful and there may be situations where admins need to control the use of specific shortcodes to avoid that they are inserted into pages and posts. One example of this could be on large websites where multiple author produce and publish content or where visitors are allowed to submit content. In this case, you do not want shortcodes used for website structure and potentially confidential content to be exposed by mistake. Justin Tadlock figured out a hack that I think you may find useful. It is a hack… and some will not like diving into such invasive measure, but it works and solved the problem.



Below is a standard definition of two new shortcodes:

add_action( 'init', 'my_add_shortcodes' );
 function my_add_shortcodes() {
 add_shortcode( 'shortcode_a', 'new_shortcode_a' );
 add_shortcode( 'shortcode_b', 'new_shortcode_b' );

If you want to disallow these shortcodes in posts and pages, you can add this code. Note that the priority on the add_filter is set to 0 to make it execute as early as possible:

add_filter( 'the_content', 'my_post_content_remove_shortcodes', 0 );
 function my_post_content_remove_shortcodes( $content ) {
 /* Create an array of all the shortcode tags. */
 $shortcode_tags = array(
 /* Loop through the shortcodes and remove them. */
 foreach ( $shortcode_tags as $shortcode_tag )
 remove_shortcode( $shortcode_tag );
 /* Return the post content. */
 return $content;

These code remove the shortcode inside the content area of the posts. However, the shortcodes are really removed here and if they are needed oustside the loop there is a problem. To enable the shortcodes again, just call it back by using this code. Again note the priority of the add_filter call. This is the hack. Remove with high priority and add back with low priority:

add_filter( 'the_content', 'my_post_content_add_shortcodes', 99 );
function my_post_content_add_shortcodes( $content ) {
 /* Add the original shortcodes back. */
 /* Return the post content. */
 return $content;

Author : Lars Vraa

Lars is passionate about web design, web development, SEO, social media and loves to look into new technologies, techniques, tools etc. and to write articles for tripwire magazine readers.

Pin It on Pinterest

Share This

Share This

Share this post with your friends!