Shortcode from a widget is wrapped in unwanted element

I’m using Black Studio TinyMCE Widget as a rich text editor widget. In a sidebar I inserted the TinyMCE widget with a [testimonial] shortcode and some content after it.

For example:

[testimonial]

Read more client testimonials (as a link)

When I switch to the HTML tab of that widget I’ve got the following:

<p>[testimonial]</p>
<p><a title="Testimonials" href="http://mm.dev/testimonials/">Read more client testimonials</a></p>

The shorcode simply displaying a random Testimonial CPT post:

add_shortcode("testimonial", "dlma_testimonial_shortcode");
function dlma_testimonial_shortcode($atts, $content = null){
    $args = array(
        'post_type' => 'testimonial',
        'post_status' => 'publish',
        'posts_per_page' => '1',
        'orderby' => 'rand'
    );
    $testimonial = new WP_Query($args);

    if($testimonial){
        return apply_filters('the_content', $testimonial->posts[0]->post_content);
    }
    return "";
}

However, when I view a page, stray <p> elements are inserted:
Edited thanks to Tom J Nowell

<div class="textwidget">
  <p>
    <blockquote>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vestibulum velit convallis sem pulvinar vitae lobortis metus varius.” <em>Person name, Person job</em></p>
    </blockquote>
  </p>
  <p>
    <a href="http://mysite.com/testimonials/" title="Testimonials">Read more client testimonials</a>
  </p>
</div>

The [testimonial] shortcode got expanded correctly, however, as it was originally wrapped into <p> element in the widget it still appears to be wrapped in it. I have tried deleting the <p> element from the widget HTML tab view, however, whenever the Save button is clicked the <p> element is inserted again.

I’ve tried to remove unwanted <p> element that wraps the shortcode with the the_content filter as following:

remove_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'wpautop' , 12);

That didn’t work. I’m guessing I’ve got the flow wrong of processing the content of a widget with a shortcode in it. I’m very confused now. How can I remove unwanted <p> elements that wrap shortcodes?

I would hugely appreciate any help!

Many thanks.

5 Answers
5

There actually are several ways to handle the WordPress editor wrapping shortcodes in <p> tags.

This code shows probably the simplest way to do it…just a simple and short function you need to drop into your functions.php file. Once you do, no more tags around your shortcodes that are on their own line!

function wpex_clean_shortcodes($content){   
$array = array (
    '<p>[' => '[', 
    ']</p>' => ']', 
    ']<br />' => ']'
);
$content = strtr($content, $array);
return $content;
}
add_filter('the_content', 'wpex_clean_shortcodes');

Source: http://www.wpexplorer.com/snippet/clean-wordpress-shortcodes

Hope that helps someone!

Leave a Comment