Join

Set the First Gallery Image of a Listing as Its Featured Image

Don't want to mess with code snippets? Request for this to be a feature of MyListing Pro.

Instructions

  1. Create a new PHP code snippet.
  2. Copy the contents of code snippet below.
  3. Paste the contents into your code snippet.
  4. Review any notes that I’ve provided.
  5. Save and enable the code snippet.
  6. Test.

Snippet

By default, MyListing does not use the Featured Image portion of the Listing, so Listing owners cannot add their own Featured Image from the front end.

There are instances where you might want to use a 3rd party solution to build custom Listing grids, and sometimes those solutions will require you to have a Featured Image in place to pull from for the media portion of the Listing card.

add_action( 'mylisting/submission/save-listing-data', function( $listing_id, $fields ){
    $listing = \MyListing\Src\Listing::force_get( $listing_id );
    if ( ! $listing ) {
         return;
     }
       if ( ! $fields['job_gallery'] ) {
        return;
    }
     global $wpdb;
    $attachment = $wpdb->get_col( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $fields['job_gallery']['value'][0] ));
   if ( $attachment && is_array( $attachment ) && isset( $attachment[0] ) ) {
  set_post_thumbnail( $listing_id, $attachment[0] );
 }
}, 10e4, 2 );
 add_action( 'mylisting/admin/save-listing-data', function( $listing_id, $listing ){
    $listing = \MyListing\Src\Listing::force_get( $listing_id );
    if ( ! $listing ) {
         return;
     }
   $gallery = $listing->get_field( 'gallery' );
   if ( $gallery && isset( $gallery[0] ) ) {
     global $wpdb;
  $attachment = $wpdb->get_col( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $gallery[0] ) );
     if ( $attachment && is_array( $attachment ) && isset( $attachment[0] ) ) {
   set_post_thumbnail( $listing_id, $attachment[0] );
  }
 }
}, 10e4, 2 );