Set featured image from first Gallery Image in Listify when using WP Job Manager Field Editor

functions.php

<?php
// This must be ran on priority 15 as Listify updates gallery images and featured image @ priority 12
add_action( 'job_manager_update_job_data', 'smyles_listify_featured_image_from_gallery', 15, 2 );

function smyles_listify_featured_image_from_gallery( $job_id, $values ){
	
	if ( ! isset( $values[ 'job' ][ 'gallery_images' ] ) ) {
		return;
	}
	
	$images = $values[ 'job' ][ 'gallery_images' ];
	
	// If gallery images removed or not set, try and remove featured image
	if ( ! isset( $images ) || empty( $images ) || empty( $images[0] ) ) {
		return delete_post_thumbnail( $job_id );
	}
	
	// Set featured image from first image in array
	$featured_image = $images[0];
	// Convert URL to attachment ID
	$attach_id = attachment_url_to_postid( $featured_image );
	
	// If different attachment ID (than currently set one), set featured image
	if ( $attach_id != get_post_thumbnail_id( $job_id ) ) {
		set_post_thumbnail( $job_id, $attach_id );
	}
	
}
No comments yet.

Leave a Reply