Eduard B.
Eduard B.

Reputation: 6803

Replace <p> </p> with <br /> with condition

In wordpress I am outputting some <div>s along the content of my shortcode. The problem is because wordpress puts paragraphs inside <p></p> tags, the line is broken where the <div> is. What I want to achieve is to replace <p> </p> which surrounds my shortcode with <br />. For example, if my content looks like this:

<p>[shortcodes attr='somethig']value[/shortcode] text<br />
[shortcodes attr='somethig']value[/shortcode] text<br />
text<br />
text [shortcodes attr='somethig']value[/shortcode] text </p>
<p>text<br />
text [shortcodes attr='somethig']value[/shortcode] text<br />
text</p>
<p> text without shortcode </p>
<p>text [shortcodes attr='somethig']value[/shortcode] text </p>

I need it to convert it in

<br/>[shortcodes attr='somethig']value[/shortcode] text<br />
[shortcodes attr='somethig']value[/shortcode] text<br />
text<br />
text [shortcodes attr='somethig']value[/shortcode] text <br />
<br/>text<br />
text [shortcodes attr='somethig']value[/shortcode] text<br />
text<br/>
<p> text without shortcode </p>
<br/>text [shortcodes attr='somethig']value[/shortcode] text <br/>

I tried to solve the problem by myself, but my preg_replace expression was capturing the whole content, instead of individual <p> </p> blocks.

Solutions with jQuery are alright too (but instead of shortcode, a <div> with a specific class must be contained in the paragraph)

LE: The following jQuery worked. However, I am still waiting for a more elegant solution in PHP.

$('p').each(function() {
    if ($(this).next().find('.measurement_value').length > 0) 
    {
        $(this).replaceWith(  '<br />' + $(this).html());
    }
});

Upvotes: 1

Views: 518

Answers (2)

Raza
Raza

Reputation: 1095

Why dont you just get rid of <p> by adding remove_filter('the_content', 'wpautop'); in functions.php

Upvotes: 0

Lucas Willems
Lucas Willems

Reputation: 7063

Try this jquery code :

$('p').each(function() {
    if ($(this).find('.class-of-the-div').length > 0) {
        $(this).replaceWith($(this).html() + '<br />');
    }
});

But, normally, Wordpress replace <br /> with <p></p> on server side.

Upvotes: 1

Related Questions