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
}
?>
  • 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 – czerspalace Jul 16 '16 at 4:01
0

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.

| improve this answer | |

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.