This file contains 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