Home › Forums › ACF PRO › Use a current ACF image as the featured image › Reply To: Use a current ACF image as the featured image
I have managed to work it out here is the answer if anyone needs it. This would go in your function.php file
// retrieves the attachment ID from the file URL
function get_image_id($image_url) {
global $wpdb;
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
return $attachment[0];
}
//Set the featured image on save of the post
add_action('save_post', 'set_featured_image_from_image');
//set featured image as main image.
function set_featured_image_from_image()
{
$has_thumbnail = get_the_post_thumbnail($post->ID);
//If there is not featured image get the other image.
if (!$has_thumbnail) {
//get the url of the ACF image and get the ID of that image
$image_url = get_field('main_image');
$image_id = get_image_id($image_url);
if ($image_id) {
set_post_thumbnail($post->ID, $image_id);
}
}
}
I am outputting just the url from the image so I had to reverse get the ID. Those who are using the full object should be able to get the ID more easily.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.