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.
Other than, of course, we’re doing so on the server.
Manipulate the DOM Using PHP
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 paragraph elements that exist in the content of the post.
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
From here, you can do several different things such as adding the post ID to a custom attribute of each paragraph element . 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.