As I have mentioned in my previous article that I have upgraded the blog design. Hence when I was developing this theme I have to make some operation and it was to set the featured image for all post.
I have image uploaded for all the posts but those images were not set as an featured image or we can say that featured image feature was not implemented in that theme. But in this theme I have planned to use the same. So I had two options at that time.
- Manually Set Featured images for all posts
- Create some code which sets featured images for all posts
So as a being web developer obviously I have choosen the second option and written one function which selects the image for the posts and assign those image as an featured image.
Let me explain in words, have a look at below steps.
1) Select all posts
2) Get first attached images of the posts using get_children() function
3) Use the set_post_thumbnail() function to set the featured image for the posts.
Have a look at below code block for the same, I have created one function which you can place in your function.php of active theme and its done.
// Get all posts so set higher number
$args = array( 'numberposts' => 5000);
// all posts
$all_posts = get_posts( $args );
foreach($all_posts as $k=>$v)
$args = array(
'numberposts' => 1,
'post_mime_type' => 'image',
'post_parent' => $v->ID,
'post_type' => 'attachment'
// Get attachments
$attachments = get_children( $args );
foreach($attachments as $attach)
// Get only first image
$attachmentsid = $attach->ID;
// Set Featured image
Here you may find some scope of improvement in code in terms of coding standards but the reason for this is, function I have not optimized in those terms. Here you can share any improvements in above code so anyone who uses this may have better help from this article.