Reputation: 101
I want to remove a div added by a plugin to the content of WordPress posts. So the post has this structure:
<div class="post">
<div class="some-class">
<p>content</p>
</div>
</div>
I want to remove <div class="some-class">
and its closing </div>
but leave the content. So it would be:
<div class="post">
<p>content</p>
</div>
using this filter:
add_filter( 'the_content', 'remove_class' , 100 );
function remove_class( $content ) {
$content = preg_replace('#<div[^>]*class="some-class"[^>]*>.*?</div>#is', '', $content);
return $content;
}
the content is also deleted, I just want the div and the closing div to be deleted. Any idea how?
Upvotes: 1
Views: 2231
Reputation: 1783
You could just try to remove class attribute, so that only <div>
is left, using code like this:
add_filter( 'the_content', 'remove_class' , 100 );
function remove_class( $content ) {
$content = preg_replace('/class=".*?"/', '', $content);
return $content;
}
Upvotes: 2
Reputation: 72336
The content is removed because you replace the entire matched string with an empty string. Use a subpattern to capture the content of the <div>
element and use it as replacement:
$content = preg_replace(
'#<div[^>]*class="some-class"[^>]*>(.*?)</div>#is',
'$1',
$content
);
However, be aware that it won't work properly if the content of <div class="some-class">
contains a <div>
element.
There is no way to parse HTML using regex
. The correct solution is to use an HTML parser (DOMDocument
f.e.) to parse the HTML fragment and create its DOM, then operate the changes on the DOM and render it back to HTML.
Upvotes: 0
Reputation: 489
@user7592255 you can try with jQuery like this:
$('p').unwrap();
If you can set an id or class on the p element you can target it more accurately
Upvotes: 0