Automatically setting the featured image without a plugin

It can be very easy to forget to set the featured image. Here is code that will do the following:

  1. Sets the featured image.
  2. If no featured image then look for category image.
  3. If no category image set the first post image.
  4. If no post image it will set a fallback image.

I did a lot of searching online and came across an article from
https://wpforce.com/automatically-set-the-featured-image-in-wordpress/ and Add Default Featured Image For Each Post In A Category

Wpforce had most of the code. I took the category code from wpsites. I then merged the category code into the featured images code.

The attachment id
Since the code uses post-id/attachment id one needs to find the image data id. Go to the media library and right click the image you want to find the data id to. Select Inspect Element then look into the html code and you should notice the data-id number of the image. This is the number you need to use.

Add the following code into your functions file.


// Inside your functions file add the following code
// 
function wpforce_featured() {
          global $post;
          $already_has_thumb = has_post_thumbnail($post->ID); // If post have a featured image use that.
              if (!$already_has_thumb)  {
              // If post does not have a featured image then get the first post image and set as featured image.
              $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" ); // Number 1 relates to taking post image number 1 and adding it as a featured image.
                          if ($attached_image) {
                                foreach ($attached_image as $attachment_id => $attachment) {
                                set_post_thumbnail($post->ID, $attachment_id);
                                //$attachment_id = attachment_url_to_postid( $image_url );
                                //   echo $attachment_id;
                               
                                }
                           } else if ( in_category('WordPress') ){ // Add your own categories.
                                set_post_thumbnail($post->ID, '21'); 
                                // Find attachment media id by right clicking the image in the Media library and selecting inspect element. Look for the data-id number. This number is then added to the post id.
                           }
                           
                           else if ( in_category('test') ) {
                           set_post_thumbnail($post->ID, '30');
                           }
                           else if ( in_category('images') ) {
                           set_post_thumbnail($post->ID, '111');
                           }
                           else if ( in_category('Uncategorized') ) {
                           set_post_thumbnail($post->ID, '111');
                           }
                        }
      }  //end function
add_action('the_post', 'wpforce_featured');
add_action('save_post', 'wpforce_featured');
add_action('draft_to_publish', 'wpforce_featured');
add_action('new_to_publish', 'wpforce_featured');
add_action('pending_to_publish', 'wpforce_featured');
add_action('future_to_publish', 'wpforce_featured');

If you do not want to add the else if categories then adjust the first else if to:


} else {
 set_post_thumbnail($post->ID, '21'); // Find attachment media id by right clicking the image in the Media library and selecting inspect element. Look for the data-id number. This number is then added to the post id.
 }

Then remove each else if that follows.

I also have a code specific for Genesis themes. (It seems to work better then the general featured image code above. I am looking into taking the Genesis featured images code and making it work for most themes in addition to Genesis themes.) This code looks for images through the url.


// GENESIS get featured image. 
// 1. Sets the featured image. 
// 2. If no featured image then get image from category. 
// 3. If no category image then get the first post image. 
// 4. If no post image or category image then set a fallback image.
// Add to your functions file.

// Resources
// https://wordpress.org/support/topic/make-first-image-in-post-featured-if-no-featured-is-set?replies=9
// http://wpsites.net/web-design/add-default-featured-image-for-each-post-in-a-category/
// https://codex.wordpress.org/Conditional_Tags


function get_src() {
  if ( has_post_thumbnail() ) {
	$src = wp_get_attachment_image_src( get_post_thumbnail_id(), 'thumb' );
	$fbimage = $src[0];
  } else {
	global $post, $posts;
	$fbimage = '';
	$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i',
	$post->post_content, $matches);
	$fbimage = $matches [1] [0];
  }
 
 if(empty($fbimage) && in_category('WordPress') ) {
    $fbimage = get_stylesheet_directory_uri().'/images/Leaves-white.jpg';
 }
 if(empty($fbimage) && in_category('images') ) {
    $fbimage = get_stylesheet_directory_uri().'/images/Tree-road-sun.jpg'; 	
 }
 if(empty($fbimage) && in_category('Uncategorized') ) {
    $fbimage = get_stylesheet_directory_uri().'/images/front-page-1.jpg'; 	
 }
 
 if(empty($fbimage)) {
 $fbimage = get_stylesheet_directory_uri().'/images/Red-back.jpg';
 /*$fbimage = site_url().'/wp-content/uploads/Red-back.jpg'; Works.
  $fbimage = site_url().'/images/Red-back.jpg'; Works
   $fbimage = CHILD_URL.'/images/Red-back.jpg'; Works - Genesis. But do not use CHILD_URL.*/
 }
 return $fbimage;
}
add_filter('genesis_get_image', 'default_image_fallback', 10, 2);
function default_image_fallback($output, $args) {
    return get_image();
}

function get_image($class="") {
    $src = get_src();
    ob_start()?>
    <a href="<?php echo get_permalink() ?>">
        <img class="featured-image <?php echo $class ?>" src="<?php echo $src ?>" alt="<?php echo get_the_title() ?>" />
    </a>
    <?php return ob_get_clean();
}

Removing the featured images

If you need to remove your featured images (I had to when I was testing the above featured images code to clear the cache in WordPress.)


add_action ('init', 'remove_featured_images' );
function remove_featured_images () {
global $wpdb;
// The following query will only unset the featured image, it will not delete it. 
$wpdb->query( "
 DELETE FROM $wpdb->postmeta 
 WHERE meta_key = '_thumbnail_id'
" );
}

The code is from: https://spicemailer.com/wordpress/how-to-remove-featured-image-from-all-posts-wordpress/ There is also variations of the above code located at the spicemailer web site.

This plugin automaticaly sets featured image for your blog posts if post thumbnail is not set manually. This extracts keywords from your article title and content and searches for image in pixabay.com


if ( !function_exists( 'add_action' ) ) {
	echo 'Hi there!  I\'m just a plugin, not much I can do when called directly.';
	exit;
}


define( 'AUTO_SET_FEATURED_IMAGE_VERSION', '1.0.0' );
define( 'AUTO_SET_FEATURED_IMAGE_DIR', plugin_dir_path( __FILE__ ) );


function bbafi_check_featurimagecheck( $post_id ) {

	// If this is just a revision, don't send the email.
	if ( wp_is_post_revision( $post_id ) )
            return;

        if(has_post_thumbnail($post_id)){
            
           return; 
        }
        
        $content_post = get_post($post_id);
        $post_content = $content_post->post_content;
        $keywords = bbafi_generate_keywords_from_text($post_content);
        
        if(count($keywords) >0 ){
            
                $random_key = array_rand($keywords, 1);
                $pixaimages = bbafi_pixabay($random_key);

                if(count($pixaimages) > 0){

                     $random_key = array_rand($pixaimages, 1);
                     $image = $pixaimages[$random_key]['image'];
                     bbafi_media_sideload_image($image,$post_id);


                }
        
        }
        
}


function bbafi_generate_keywords_from_text($text){
	
	
	    // List of words NOT to be included in keywords
      $stopWords = array('i','a','about','an','and','are','as','at','be','by','com','de','en','for','from','how','in','is','it','la','of','on','or','that','the','this','to','was','what','when','where','who','will','with','und','the','www', "such", "have", "then");
   
   
      //Let us do some basic clean up! on the text before getting to real keyword generation work
      $text = strip_tags( $text );
      $text = preg_replace('/\s\s+/i', '', $text); // replace multiple spaces etc. in the text
      $text = trim($text); // trim any extra spaces at start or end of the text
      $text = preg_replace('/[^a-zA-Z0-9 -]/', '', $text); // only take alphanumerical characters, but keep the spaces and dashes tooĂ¢â‚¬Â¦
      $text = strtolower($text); // Make the text lowercase so that output is in lowercase and whole operation is case in sensitive.
   
      // Find all words
      preg_match_all('/\b.*?\b/i', $text, $allTheWords);
      $allTheWords = $allTheWords[0];
      
	    //Now loop through the whole list and remove smaller or empty words
      foreach ( $allTheWords as $key => $item ) {
          
          $item = trim($item);
          
          if ( $item == '' || in_array(strtolower($item), $stopWords) || strlen($item) <= 3 ) {
              
              unset($allTheWords[$key]);
              
          }
          else
          {
              $allTheWords[$key] = $item;
          }
      }   
	  
	    // Create array that will later have its index as keyword and value as keyword count.
      $wordCountArr = array();
	  
	    // Now populate this array with keywrds and the occurance count
      if ( is_array($allTheWords) ) {
          foreach ( $allTheWords as $key => $val ) {
              $val = strtolower($val);
              if ( isset($wordCountArr[$val]) ) {
                  $wordCountArr[$val]++;
              } else {
                  $wordCountArr[$val] = 1;
              }
          }
      }
	  
	    // Sort array by the number of repetitions
      arsort($wordCountArr);
	  
	    //Keep first 10 keywords, throw other keywords
      $wordCountArr = array_slice($wordCountArr, 0, 10);
	  
  return $wordCountArr;
}


function bbafi_pixabay($keywords) {
    
     
        
        $keywords = str_replace(' ','+',$keywords);
        $apikey   = "6855592-14276b9cbb58e5c2554e46166";
      
        $limit  = 10;
        $offset = 1;
           
        
        $url = "https://pixabay.com/api/?key=".$apikey."&q=".$keywords."&per_page=".$limit."&page=".$offset."&image_type=photo";
        
        $pixaImages = json_decode(file_get_contents($url),true);
        

        $data = array();  
        if(count($pixaImages['hits']) > 0)
        {

            $data['status'] = 1;
            foreach($pixaImages['hits'] as $images){  
            
               $data[] = array(
                                        'image'  => $images['webformatURL'],
                                        'id'     => $images['id'],
                                        'type'   => 'image'
                                      );
            
            }
        
        } 
        
        
        return $data;

}


function bbafi_media_sideload_image($url, $post_id, $filename = NULL) {

            require_once( ABSPATH . 'wp-admin/includes/file.php' );

            $tmp = download_url($url);
            if (is_wp_error($tmp)) {
                // And output wp_error.
                return array('status' => 'false', 'message' => 'An Unknown error occurred while uploading media file.');
            }

            preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $url, $matches);
            $url_filename = basename($matches[0]);
            $url_type = wp_check_filetype($url_filename);


            if (!empty($filename)) {
                $filename = sanitize_file_name($filename);
                $tmppath = pathinfo($tmp);
                $new = $tmppath['dirname'] . '/' . $filename . '.' . $tmppath['extension'];
                rename($tmp, $new);
                $tmp = $new;
            }
            $file_array['tmp_name'] = $tmp;

            if (!empty($filename)) {

                $file_array['name'] = $filename . '.' . $url_type['ext'];
            } else {

                $file_array['name'] = $url_filename;
            }


            $post_data = array(
                'post_title' => get_the_title($post_id),
                'post_parent' => $post_id,
                'post_mime_type' => $url_type['type'],
                'post_content' => '',
                'post_status' => 'inherit'
            );

            // Required libraries for media_handle_sideload.
            require_once( ABSPATH . 'wp-admin/includes/file.php' );
            require_once( ABSPATH . 'wp-admin/includes/media.php' );
            require_once( ABSPATH . 'wp-admin/includes/image.php' );


            // $post_data can override the items saved to wp_posts table, like post_mime_type, guid, post_parent, post_title, post_content, post_status.
            $att_id = media_handle_sideload($file_array, $post_id, null, $post_data);

          
            // If error storing permanently, unlink.
            if (is_wp_error($att_id)) {
                // Clean up.
                @unlink($file_array['tmp_name']);

                // And output wp_error.
                return array('status' => 'false', 'message' => 'An Unknown error occurred while uploading media file.');
            }

         
            set_post_thumbnail($post_id, $att_id);
            return array('status' => 'true');
}

//attach hook to call after post is saved
add_action( 'save_post', 'bbafi_check_featurimagecheck' );