1

I am trying to get the featured images of custom post type images. I am using this code. All of my posts have images but I am unable to show.

<?php
$posts_array = get_posts(

    array(
        'posts_per_page' => -1,
        'post_type' => 'services',
        'tax_query' => array(
            array(
                'taxonomy' => 'service_categories',
                'field' => 'name',
                'terms' => $device_name,
            )
        )
    )

);

//show devices
//print_r($posts_array);
foreach ($posts_array as $key) {
    //print_r($key);
    if ( has_post_thumbnail() ) {
        the_post_thumbnail();
        echo "yahoo";
    } 

    ?><div class="devices_name_" style="cursor: pointer">
        <div><?php echo the_post_thumbnail($key->ID); ?></div>
        <?php echo $key->post_title; ?>
        <input type="hidden" value="<?php echo $key->ID; ?>" class="devices_ids_"/>
    </div>

<?php
}
?>
1
  • 2
    Can you try echo get_the_post_thumbnail($key->ID) and see if you get the image? Just the_post_thumbnail() is used in the loop with WP_Query Jul 16, 2016 at 4:01

1 Answer 1

1

Here are some thoughts :

But in your case I don't really see why you use get_posts() most of the time we use it to get post data and make other treatments. You'd better use your own instance of WP_Query here like this :

    <?php
    $_posts = new WP_Query (

        array(
            'nopaging'  => true,
            'post_type' => 'services',
            'tax_query' => array(
                array(
                    'taxonomy' => 'service_categories',
                    'field' => 'name',
                    'terms' => $device_name,
                )
            )
        )

    );

    if ( $_posts->have_posts() ) :
        while ( $_posts->have_posts() ) : $_posts->the_post(); ?>
            <div class="devices_name_" style="cursor: pointer">
                <?php if ( has_post_thumbnail() ) : ?>
                    <div><?php the_post_thumbnail(); ?></div>
                <?php endif; ?>
                <?php the_title(); ?>
                <input type="hidden" value="<?php the_ID(); ?>" class="devices_ids_"/>
            </div>
       <?php endwhile; wp_reset_postdata();
   endif;

this way you could use functions that work within the loop. Be careful the_post_thumbnail() takes a size parameter. By default it's "post-thumbnail" size.

Your Answer

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

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