I am getting an empty extra version of each div when this code runs as a Wordpress template. I can hide it with css div:empty {display: none;} but I would like to know why this happens and how to fix my error. My output is
<div id="primary" class="content-area">
<main id="content" class="clearfix">
<?php
$args = array (
'post_type' => array('read1','read2'),
'post_status' => 'publish',
'pagination' => true,
'posts_per_page' => 2,
'order' => 'ASC',
'orderby' => 'title',
);
?>
<?php $wp_query = new WP_Query($args); ?>
<?php while (have_posts()) : the_post();
echo '<div class="read1-hold">';
echo get_post_meta($post->ID, 'book1_title', true);
echo '</div>';
echo '<div class="read2-hold">';
echo get_post_meta($post->ID, 'book2_title', true);
echo '</div>';
?>
<?php endwhile;?>
</main>
</div>
<?php get_footer();
</div>
You're getting 'empty' book titles where there is no book2_title or book1_title for the post.
Try something like:
$title= get_post_meta($post->ID, 'book2_title', true);
if (!empty($title))
echo '<div class="read1-hold">'.$title.'</div>';