Created
October 25, 2017 09:11
-
-
Save MichaelConte/6a9e189ac437724f90558a4a155de358 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function set_featured_image_for_posts() { | |
// Get all posts so set higher number, | |
// you can increase to any number if you have big amount of posts | |
$args = array( 'numberposts' => 5000); | |
// all posts | |
$all_posts = get_posts( $args ); | |
foreach($all_posts as $k=>$v) | |
{ | |
$args = array( | |
'numberposts' => 1, | |
'order'=> 'ASC', | |
'post_mime_type' => 'image', | |
'post_parent' => $v->ID, | |
'post_type' => 'attachment' | |
); | |
// Get attachments | |
$attachments = get_children( $args ); | |
$i=0; | |
foreach($attachments as $attach) | |
{ | |
// Get only first image | |
if($i==0) | |
$attachmentsid = $attach->ID; | |
$i++; | |
} | |
// Set Featured image | |
set_post_thumbnail($v->ID,$attachmentsid); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
by downgraf - Set Featured Image Automatically With PHP Snippets