0

I have the following loop working as I want it but I need the 'activists' list item to include <?php the_post_thumbnail(); ?>.

What would be the best way to write this?

<?php

        $terms = array('news', 'activists', 'resources', 'posts' );

        if ( !empty( $terms ) && !is_wp_error( $terms ) ){

            foreach ( $terms as $term ) {

                $my_query = new WP_Query('posts_per_page=5&post_type='.$term);

                while ($my_query->have_posts()) : $my_query->the_post();

                echo '<li class="item ' . $term . '">'; ?>

                <a href="<?php the_permalink(); ?>"><strong><span><?php echo the_title(); ?></span></strong></a>

                <?php echo '</li>';

                endwhile; wp_reset_query();
            }

        }

        ?>

Thanks in advance.

1
  • 1
    @Pieter's answer tells you what to do. As an aside, note that "Terms" has it's own meaning (in WP-Lingo, at least) and is not equivalent to "Post Type". Your variable-naming is suboptimal. Jul 21, 2014 at 15:58

3 Answers 3

3

You can make use of get_post_type( $post ) to check whether a post belongs to a certain post type

Inside your loop, you can do the following check

while ($my_query->have_posts()) : $my_query->the_post();

if ( 'activists' == get_post_type() ) {

    /* Custom code for 'activists' post type. */

} else {

    /* Custom code for the other post types. */
}

endwhile; wp_reset_query();
2

I would do something like OmAk suggested but I would add some fallback :

$activists_thumbs = has_post_thumbnail() ? the_post_thumbnail() : 'path/img_fallback.jpg';

It's better to check if you have something before actually using it.

EDIT: wp_reset_postdata() is enough (instead of wp_reset_query() )

2
  • Make "maybe" a "definitely" an I'd upvote this. Jul 21, 2014 at 15:49
  • It's done now :)
    – JMau
    Jul 21, 2014 at 15:53
0

You can use this:

<a href="<?php the_permalink(); ?>" title="<?php echo the_title_attribute(); ?>">
    <?php the_post_thumbnail(); ?>
</a>

This will place the featured image with a link to the main post.

More details about how you can use image_size when calling the function: the_post_thumbnail

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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