Home › Forums › General Issues › Set featured image of CPT from existing image › Reply To: Set featured image of CPT from existing image
i take it this is a one off, meaning that you want to rip through the whole list of posts and assign the field X image to the featured image.
Why dont you write a script (one run) that will load in all posts for assigning retroactively, check for the custom image, if it exists, set it as the thumbnail of the post.
NOTE* whenever writing custom scripts like this, backup your database and when the script has run successfully, delete the file from your server.
something like this, sitting in the root would probably work, this was written of the top of my head so check the code.
<?php
require('wp-load.php'); // get the wp api
$args = array(
'post_type' => 'your_post_type',
'posts_per_page' => -1
);
$queryWP = new WP_Query($args);
while ($queryWP->have_posts()) : $queryWP->the_post();
// get the post id
$postID = get_the_ID();
// get the custom field image as an object
$field_image = get_field("your_field_key");
// get the image id
$imageID = $field_image['ID'];
// check if the post does not have a featured image and that the image id is not empty
if(!has_post_thumbnail($postID) && $imageID!=''):
// set the post featured image
set_post_thumbnail( $postID , $imageID );
// output confirmation
echo "post set - ".$postID."<br>"
echo "thumbnail id as featured image - ".$iamgeID."<br>";
endif;
endwhile;
?>
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 Cookie Policy. If you continue to use this site, you consent to our use of cookies.