WordPress filters are so damn convenient and make devs’ life so much easier that rather often you can see developers forgetting to turn the thinking mode on before use it. I would lie if I tell personally I had never done this mistake before and that’s another reason for this post.
Just as you won’t eat soup with a fork, you won’t use any of the WordPress filters where it’s not suitable. Think of these too examples.
Case 1: limit characters in content for guests [Appropriate usage]
Imagine, you are giving some valuable information to your visitors and want to make sure that only registered users will get the whole post content, all others should see just part of it, say 300 characters and then the sign-up button.
You can use a simple piece of code to check whether the user is logged in, if no — limit the characters by the_content filter
Case 2: filter image links from the content [Inappropriate usage]
You’ve got your company blog with images in your posts, of course. By default WP surrounds every upload image by <a> tags so it’s clickable. One day you find out that linking to images files may harm your SEO and decide to get rid of the links. Google will happily advise you solution like this.
the_content filter will affect existing and new posts, as you understand, as it’s called every time the page loading. These are con and pron in one glass. Good part that it affects all posts all the way, bad news that it’s rather demanded for resources.
All WordPress filters and this very the_content filter too are designed to filter the content.
This means that on page load the actual content first is loaded, then the filter is applied to it and the result is shown to user. This process is going on every single page load and demands certain CPU and RAM resources. The higher traffic you get, the more resources you need to hold such operations. That doesn’t mean you should not use filters at all, of course, no. But you should use them in the right place and time.
Case 1 describes the situation where you don’t want your content changed forever, but really being filtered in certain case. Case 2 on the contrary shows that you are using filtering when really you want to change your content permanently.
Neither WordPress the_content filter nor others should not be used for permanent changes. It’s simply senseless. You overload your server and slow down your page load by using filters when permanent changes are needed.
What is right to use in this case? Just change your post content permanently. It should be executed once and all your existing posts will be updated (check the functions here).
Remember, these are just tools that can be used correctly by thinking developer.
Leave a Reply