Skip to content

Instantly share code, notes, and snippets.

@bhongy
Last active September 15, 2023 03:36
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save bhongy/6761732 to your computer and use it in GitHub Desktop.
Save bhongy/6761732 to your computer and use it in GitHub Desktop.
Wordpress: Check if the_content is empty / do something only when the_content is empty
<?php if ( get_the_content() ) { ?>
// do or output something
<?php } ?> // break php tag for HTML block
@apermo
Copy link

apermo commented Sep 1, 2017

You could perfectly replace

$thecontent = get_the_content();
if(!empty($thecontent))

by

if ( !empty( get_the_content() ) )

And Thank you for the snippet :)

@ob-ivan
Copy link

ob-ivan commented Nov 17, 2017

@apermo, please bear in mind this syntax is only valid since PHP 5.5. WordPress is pretty conservative with back-compat, so if you produce a plugin that may be installed on older version of PHP, please consider using an additional variable like @bhongy did.

@stefanfisk
Copy link

the_content() also applies the the_content filter to the result of get_the_content(), so the method above might not actually work :/

@studiovanzwet
Copy link

studiovanzwet commented Nov 22, 2018

`

`

@netzgestaltung
Copy link

just to summarize:

  $the_content = apply_filters('the_content', get_the_content());
  if ( !empty($the_content) ) {
    echo $the_content;
  }

@chunkybyte
Copy link

the_content() also applies the the_content filter to the result of get_the_content(), so the method above might not actually work :/

Is there a use-case where this should be a problem for an empty check? Just wondering if I still use the_content() for displaying the content and empty check using get_the_content(), shouldn't be an issue right.

@drdogbot7
Copy link

No need to use empty(), this works fine:

if ( get_the_content() ) {
//  do whatever!
}

If your post is empty, get_the_content will return an empty string, and in an IF statement PHP will interpret an empty string as FALSE.

https://www.php.net/manual/en/language.types.boolean.php

@alimoshen
Copy link

That worked for me @drdogbot7 !
Thanks

@bhongy
Copy link
Author

bhongy commented Jul 11, 2021

Thanks, @drdogbot7! Updated the gist per your suggestion.

@quyetlv12
Copy link

if ( get_the_content() ) {
//  do whatever!
}

thanks you for question

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment