Get first image of custom post type wordpress

0 Votes
    305 Views

I have this code

function display_categoria($args) {
$query = new WP_Query(array(
    'post_type' => 'job_listing',
    'post_status' => 'publish',
    'posts_per_page' => 5
));


while ($query->have_posts()) {
  echo $query->the_post();
   $id=get_the_id();
   echo $query1=get_permalink();
  }

 wp_reset_query();
}

add_shortcode( 'este', 'display_categoria' );

in theory i can solve it placing in the loop

 if ( has_post_thumbnail() ) {
the_post_thumbnail();
                            } 

but many entries not have a thumbnail (featured images), Can understand?

1

Answers


  1. + -

    This should retrieve the url of the first image for each post. Insert it after the “$id=get_the_id();” line

    $args = array(
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'posts_per_page' => -1,
        'post_status' => null,
        'post_parent' => $id 
    ); 
    $images = get_posts( $args );
    if ( $images ) {
        $first_image_id = $images[0];
    
        //do something with the image
    
        wp_reset_postdata();
    }
    
Please signup or login to answer this question.