GeoDirectory keeps listing images in its own attachments table, so calling set_post_thumbnail() on its own doesn’t add the image to the listing’s gallery. Save the images through the listing’s post_images field instead. GeoDirectory then imports the file, adds it to the gallery, and sets the first image as both the GeoDirectory featured image and the WordPress post thumbnail.
How the post_images value works
post_images is a string of images separated by ::. Each image is url|attachment_id|title|caption. A new image only needs its URL. The first image in the string becomes the featured image.
Add a new featured image and keep the existing gallery
This snippet puts a new image first and keeps the images the listing already has after it:
/**
* Make an image the featured image of a GeoDirectory listing.
*
* @param int $post_id Listing ID.
* @param string $image_url Full URL of the image to import.
*/
function my_gd_set_featured_image( $post_id, $image_url ) {
// Current images as "url|id|title|caption::url|id|title|caption".
$current = GeoDir_Media::get_field_edit_string( $post_id, 'post_images' );
$images = esc_url_raw( $image_url );
if ( $current ) {
$images .= '::' . $current;
}
wp_update_post(
array(
'ID' => $post_id,
'post_images' => $images,
)
);
}
// Example.
my_gd_set_featured_image( 123, 'https://example.com/wp-content/uploads/photo.jpg' );
To replace the whole gallery, pass only the new URLs, separated by ::, with the featured image first. Images that were in the gallery but are missing from the new string are deleted.
When you create a listing with wp_insert_post(), you can pass post_images in the same array as the title and content.
Things to check
- The image URL must be reachable from your server, because GeoDirectory downloads it.
- The new featured image is saved in the uploads folder for the listing’s publish date, not the current month. WordPress does this when it sideloads an image for an existing post.
- Old images that already exist on the listing keep their files. Only their order changes.
If you’re importing a lot of listings, the CSV import may be easier. See How to format the CSV file for importing listing images.