Kohei Murakami
Kohei Murakami

Reputation: 349

How to replace HTML in WordPress outside Contents?

I'd like to insert barba.js wrapper to enable barba around main tag.

Current code is like below.

<main>
    <article>
        ........
    </article>
</main>

And what I desire is like below.

<div id="barba-wrapper">
    <div class="barba-container">
        <main>
            <article>
                ........
            </article>
        </main>
    </div>
</div>

If main tag is inside 'the_content' filter, I could code like below.

add_filter('the_content', function($content) {
    $content = str_replace('<div id="barba-wrapper"><div 
    class="barba-container"><main>', '<main>', $content);
    $content = str_replace('</main>', '</main></div></div>', $content);
    return $content;
});

However, <main> is not inside the_content filter, above function is not working.

Is there anyway to replace it? and is there any warning about this?

Upvotes: 1

Views: 6579

Answers (1)

Emma
Emma

Reputation: 27753

My guess is that an expression similar to:

(<main>(.*?)<\/main>)

might work here.

TEST

$re = '/(<main>(.*?)<\/main>)/s';
$str = '

<main>

some content we wish goes here

</main>';
$subst = '<div id="barba-wrapper"><div class="barba-container">$1</div></div>';
$result = preg_replace($re, $subst, $str);

echo $result;

based on which our code might look like:

$re = '/(<main>(.*?)<\/main>)/s';
$subst = '<div id="barba-wrapper"><div class="barba-container">$1</div></div>';
$result = preg_replace($re, $subst, $content);

echo $result;

For additional explanation, please see this link.

Upvotes: 4

Related Questions