Problem: You want to check if the content in a WordPress post is empty. Seems easy, but do a Google search on the topic and you’ll see the question asked and — incorrectly — answered several times.
The fact is, I know how to do this. I was just hoping there was a built-in function in WordPress that I didn’t know about. Apparently not, so I wrote my own.
Why isn’t it easy and obvious how to check for the content being empty? Well, you could do this:
if ($post->post_content == '') { ... }
That will work. If the content is really empty. That means a zero-length string. As in strlen($post->post_content) == 0
. Which it might be. But probably not.
If you’ve worked with real world site content, or even someone else’s Word documents before, you know that blank space is invisible, and a lot of times there’s a lot of blank space in a document that is not truly “empty.” Spaces, line breaks, HTML paragraphs with nothing but a non-breaking space in them. It all takes up space, and makes the content look empty, even when it’s not.
That last example is the critical one here. A WordPress post may look like it has no content, but if someone pressed Enter while the cursor was in the content box and then saved the page, it most likely has at least one <p> </p>
in it.
So what you need is a function that takes all of that invisible cruft into account. Since it doesn’t seem like WordPress has such a function built in, I wrote my own, which I have made as compact as possible:
function empty_content($str) {
return trim(str_replace(' ','',strip_tags($str))) == '';
}
This function takes the string you pass into it, strips out all HTML tags, then removes any non-breaking space entities, and then trims all whitespace. If there’s nothing but that stuff, then it becomes an empty string. If there’s any “real” content, the string won’t be empty. Then it just compares whatever it has left against an actual empty string, and returns the boolean result.
So now if you want to check if the WordPress content is really empty, you can do this:
if (empty_content($post->post_content)) { ... }
This will return true
if the content is empty; false
if it’s not.
Update (8/31/2017): This post continues to be one of the most frequently viewed on my blog, and I’ve been meaning for ages to amend it with this important note. As written here, you’ll get an erroneous true
returned if the only content is in HTML, for instance, an image. If you want the function to return false
if there’s no text content, then leave it as-is. But you can add a second input parameter to the strip_tags()
function to tell it to leave certain HTML tags alone. If you want to allow image tags, for instance, the modified code would read as such:
function empty_content($str) {
return trim(str_replace(' ','',strip_tags($str,'<img>'))) == '';
}