MD. Atiqur Rahman
MD. Atiqur Rahman

Reputation: 2173

Set featured image via post content programmatically

I was trying to add featured image from post content. My idea is to set the first image of the content as featured image of the post.

I wrote this in my funtions.php

    add_action('publish_post', 'auto_featured_image_publish_post');
         function auto_featured_image_publish_post($post, $post_id) {
           $thumnail_id = //something I need help with
           set_post_thumbnail( $post, $thumbnail_id );
         }

This is just an idea how I want to do this.

Please help. Thanks

Upvotes: 2

Views: 1700

Answers (1)

Mostafa
Mostafa

Reputation: 909

Check this url

https://www.gavick.com/blog/wordpress-quick-tip-4-automatically-set-the-first-post-image-as-a-featured-image

OR you can use this code to get the url of the first image from any HTML code

<?php
$postcontent = "";
preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $postcontent, $image);
// you can use the exist pattern or use this
// '/< *img[^>]*src *= *["\']?([^"\']*)/i'
echo $image['src'];
?>

Upvotes: 1

Related Questions