Last active
August 29, 2015 14:21
-
-
Save moughamir/f671c6f7e37bd608072f to your computer and use it in GitHub Desktop.
Set Featured Image Automatically
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
<?php | |
/** | |
* @Author Avinash | |
* @see http://wp-snippets.com/set-featured-image-automatically/ | |
* @package wordpress | |
*/ | |
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