A good[ish] website
Web development blog, loads of UI and JavaScript topics
Part of the PHP basics series.
Here we’ll use the empty()
:
if (empty($args)) {
// Do something if empty
} else {
// Do something else if not empty
}
But that’s kinda long way to do it. Many times it’s more handy to ask if it’s not empty.
// Note the exclamation mark
if (!empty($args)) { /* do something here */ }
Much more compact.
Get some author profile fields. In this case, it's important to check if the variables have content in them, or otherwise leave empty elements into the code (or the "Tel:" would be there for nothing).
$author_id = 2;
$address = get_the_author_meta('address', $author_id );
$phone = get_the_author_meta('phone', $author_id );
$fax = get_the_author_meta('fax', $author_id );
if (!empty($phone)) {
echo '<address>' . wpautop($address) . '</address>';
}
if (!empty($phone)) {
echo 'Tel: ' . $phone;
}
if (!empty($fax)) {
echo 'Fax: ' . $fax;
}
Use the equals to operator ==
:
// Is equal to nothing
if ( $post->post_content == "" ) :
// Do something if empty
else :
// Do something if not empty
endif;
Display the "Read More →" button only if the post content has something in it. It may be, that only the excerpt has content, and there is no need for the read more link.
<?php
if ($post->post_content == "") :
// Nothing
else :
?>
[" class="more-link">Keep Reading →](<?php the_permalink(); ?)
<?php endif; ?>
Comments would go here, but the commenting system isn’t ready yet, sorry.