Clean Up WordPress Shortcode Formatting

[font_icon icon=warning-sign] Hey guys this post explains how to do something incorrectly, please check out my new post here – Clean WordPress Shortcodes

As I was working on a new premium WordPress theme for Themeforest I was having issues with my Pricing Table shortcode as it kept adding extra spacing due to stray empty paragraph (p) tags that were being added automatically by WordPress. Doing a little searching I found a great solution on the TF forum.

Clean Up WordPress Shortcodes Function

Simply copy and paste the following code into your functions.php file or wherever your hold your shortcodes. This function will clean up the output of your shortcodes, which is especially important for nested shortcodes.

Note: If you want to be able to add some spacing manually within your shortcodes you can see my post on Adding A Line Break Shortcode To WordPress.

Code provided by OrganicBeeMedia on the TF forum. Originally created by http://donalmacarthur.com.

//Clean Up WordPress Shortcode Formatting - important for nested shortcodes
//adjusted from http://donalmacarthur.com/articles/cleaning-up-wordpress-shortcode-formatting/
function parse_shortcode_content( $content ) {

   /* Parse nested shortcodes and add formatting. */
    $content = trim( do_shortcode( shortcode_unautop( $content ) ) );

    /* Remove '' from the start of the string. */
    if ( substr( $content, 0, 4 ) == '' )
        $content = substr( $content, 4 );

    /* Remove '' from the end of the string. */
    if ( substr( $content, -3, 3 ) == '' )
        $content = substr( $content, 0, -3 );

    /* Remove any instances of ''. */
    $content = str_replace( array( '<p></p>' ), '', $content );
    $content = str_replace( array( '<p>  </p>' ), '', $content );

    return $content;
}

//move wpautop filter to AFTER shortcode is processed
remove_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'wpautop' , 99);
add_filter( 'the_content', 'shortcode_unautop',100 );
AJ Clarke | WPExplorer
Hey. My name is AJ and I am the boss around here. I own and operate WPExplorer. A website dedicated to everything I love about WordPress.
AJ Clarke | WPExplorer
AJ Clarke | WPExplorer

Add AJ Clarke | WPExplorer to your circles!

3 Comments

  1. Robb Fritz says:

    I think this relates to the other issue I wrote you about, which I thought was a theme conflict. Where would this code go (or the correct code on your other post)? I’m afraid I have a feeble understanding of shortcodes.

    • AJ Clarke | WPExplorer says:

      I’ve updated the theme, if you download the latest version and replace your file at functions/shortcodes.php it should fix the issue. Or you can open a ticket at WPThemehelp.com

Leave a Reply