0

I have created a CTA in WordPress where the HTML looks like,

<p>
<a class="cta" href="...">CTA Button</a>
</p>

Further, I've styled the class cta. But now, the CSS is not looking great whenever the text wraps. Only now, I'm realizing that for a better looking CTA the CSS class should have been used in the <p> and not in the <a> tag.

Since I've followed this huge number of elements, changing them manually is nearly impossible. I'm sure this can also be achieved using JS, but I'm using AMP which makes such implementation really difficult.

Hence, I'd like to if this can be achieved using PHP or CSS?

Nirmal Kumar
  • 139
  • 2
  • 7

1 Answers1

0

PHP solution:

<?php
// example code

$html=<<<EOT
<p>
<a class="cta" href="...">CTA Button</a>
</p>
<p>
<a class="dontreplaceme" href="...">CTA Button</a>
</p>
<p><a class="cta" href="...">
CTA Button</a>
</p><p><a class="cta" href="...">CTA Button</a></p>
<p><a class="cta" href="...">CTA Button</a></p>
EOT;
$delim = 'class="cta"';
// remove white spaces between tags
$html = explode($delim, preg_replace('/\>\s+\</m', '><', $html));
$new = [];
foreach($html as $seg) {
    // check end of segment for a match
    if(strcmp(substr($seg, -6), '<p><a')>0) {
        $seg = substr($seg,0,-6).'<p ' . $delim . '><a';
    }
    $new[]= $seg;
}
$new = implode("",$new);
print_r($new);

Example: https://www.tehplayground.com/XPVv3i8kRxXI0mJ7


Javascript solution (archived) since you want a PHP one

This will run after the page has rendered and will remove 'cta' from the 'a' tags and place it in the closest 'p' parent

window.addEventListener('load', () => { 
   document.querySelectorAll('a.cta')
   .forEach(e=>{ 
      e.classList.remove('cta');
      e.closest('p').classList.add('cta');
   }); 
})

Which compresses down to a tidy one-liner

window.addEventListener('load', () => { document.querySelectorAll('a.cta').forEach(e=>{e.classList.remove('cta');e.closest('p').classList.add('cta');}); })
Kinglish
  • 23,358
  • 3
  • 22
  • 43