-1

I'm a beginner in PHP and I would like to set up several functions to replace specific code bits on WordPress (including plugin elements that I can't edit directly).

Below is an example (first line: initial result, second line: desired result):

<a href="" class="vcard author"><span class="fn" itemprop="name">Gael Beyries</span></a>

<div class="vcard author"><span class="fn" itemprop="name">Gael Beyries</span></div>

PS: I came across this topic: Parsing WordPress post content but the example is too complicated for what I want to do. Could you present me an example code that solves this problem so I can try to modify it to modify other html elements?

Syscall
  • 19,327
  • 10
  • 37
  • 52

1 Answers1

1

Although I'm not sure how this fits into WP, I have basically taken the code from the linked answer and adapted it to your requirements.

I've assumed you want to find the <a> tags with class="vcard author" and this is the basis of the XPath expression. The code in the foreach() loop just copies the data into a new node and replaces the old one...

function replaceAWithDiv($content){
    $dom = new DOMDocument();
    $dom->loadHTML($content);
    $xpath = new DOMXPath($dom);
    $aTags = $xpath->query('//a[@class="vcard author"]');

    foreach($aTags as $a){
        // Create replacement element
        $div = $dom->createElement("div");
        $div->setAttribute("class", "vcard author");
        // Copy contents from a tag to div
        foreach ($a->childNodes as $child ) {
            $div->appendChild($child);
        }
        // Replace a tag with div
        $a->parentNode->replaceChild($div, $a);
    }
    return $dom->saveHTML();
}
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55