• I would like to make a div conditional on whether there is an image or not. If there is a featured image, I want the div (containing the image) to appear. If there is no image, I don’t want the div.

    I have been working on this code:

    <div class="div-1">
    	    <?php $posts = get_posts( "cat=50&numberposts=1" ); ?>
                <?php if( $posts ) : ?>
                <?php foreach( $posts as $post ) : setup_postdata( $post ); ?>
                  <a href="<?php echo get_permalink($post->ID); ?>" >
    			     <?php if ( has_post_thumbnail()) : 
    
    				 the_post_thumbnail('titleof-thumb'); endif; ?>
    			  </a>
                <?php endforeach; ?>
                <?php endif; ?>
        </div>

    I’ll spare you the things I tried to add after the if statement “if (has_post_thumbnail()) : ” but I get errors when I try to put a div in there. I want to say “if has thumbnail, then show div with thumbnail” instead of (already have) “if has thumbnail, show thumbnail.

    Thanks for any help

Viewing 3 replies - 1 through 3 (of 3 total)
  • Hi,

    Yuo haven’t indicated what errors you get nor where you put the divs, but if the anchor tag works then putting a div tag around the anchor should work….

    <div><a……….> </div>

    You do use echo (or print), right? Or alternatively, use the ?> and <?php tags to close and re-open the PHP code at the correct positions.

    For example, using echo:

    if ( has_post_thumbnail()) {
    echo ‘<div>’;
    the_post_thumbnail(‘titleof-thumb’);
    echo ‘</div>’;
    }

    Edit to add: Your code is syntactically wrong in that the tag – which is HTML and not PHP – appears within the PHP code. You should place a ?> tag (= PHP closing tag) before the , in order for your code to be syntactically correct.

    Edited again to add: I mean the < / a > tag in the first line of my previous edit, this editor deletes it if I write it the normal way…

    Thread Starter JMunce

    (@jmunce)

    That worked, thank you

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘How to put a div inside the php loop?’ is closed to new replies.