When it comes to manipulating the DOM, the first thing many of us likely think of is using JavaScript to do whatever it is we need to do.

Not only does the language natively support functions for doing this, newer features of ES6 give us more powerful ways to build client-side scripts. And if you’re using jQuery with WordPress, then you have the same library of functions for, ahem, querying the DOM that we’ve had for years.

But manipulating the DOM on the client-side isn’t always the best option. Instead, you may want to do so on the server-side. And because of some of the features built into PHP, it’s not much different from how we do things using JavaScript.

Manipulate the DOM Using PHP: Manipulate the DOM Using PHP: DOmDocument

Other than, of course, we’re doing so on the server.

Manipulate the DOM Using PHP

So if you’re ever working with the content for a post (a post type or a custom post type, for that matter) and you need to manipulate tags much like you would with JavaScript, then using the DomDocument library is one of the most powerful tools are your disposal.

Let’s say, for example, you want to iterate through all of the secondary headings that exist in the content of your posts.

It’s easy to do this using said library. First, you’ll want to make sure you’ve got the library set up in your class (or just in your collection of functions):

Next, set up a hook for the content:

And within that function, make sure to load the content of the post into the library and then look for all of the h2 elements much like you would using JavaScript:

From here, you can do several different things, the least of which is not, say, converting them to an order list and then returning the updated content to WordPress. The full function would then look something like this:

Of course, there are other things you can do, too. It’s one thing to manipulate the markup before sending it to the browser. It’s another thing, though, to add attributes to the data if they don’t already exist.

That’s, no pun intended – except maybe only sort of – content for another post.