0

Inside a WordPress loop, I'd like to conditionally check to see if the post has a title, in order to provide necessary wrapping HTML. If the post does not have a title, I don't want any of the wrapping HTML to appear.

2

While you're in The Loop you can check against the WP_Post Object like so:

<?php while( have_posts() ) : the_post(); ?>

    <?php if( ! empty( $post->post_title ) ) : ?>

        <h1><?php the_title(); ?></h1>

    <?php endif; ?>

<?php endwhile; ?>
3

While checking $post->post_title, as in Howdy_McGee's answer, is probably safe in most cases, there may be some instances where a title is being modified by the_title filter. In that case, you have to get the title via the API to determine if it's really empty.

$title = trim( get_the_title() );

if( ! empty( $title ) ){
    echo 'there is a title';
} else {
    echo 'empty title';
}
2

You can add the before and after html tags to the_title() function. If the post_title is empty, nothing will be outputted.

the_title('<h1>', '</h1>');
  • Yes, but I'd like to add the_permalink() as well as other wrapping HTML inside, rather than a single opening and closing tag. – Daniel Genser Jun 14 '17 at 18:37
0

To expand @Milo's answer.

echo $title = ( ! empty( trim( get_the_title())) ? "there is a title" : "empty title";

or

echo $title = ( ! empty( trim( get_the_title())) ?: "empty title";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.