I am trying to call the save_post or publish_post hook with my function it the function cannot be triggered.
My function works well on single.php but it only assigns thumbnails after browsing the post. So I decided to put it inside functions.php but I could not get it triggered with save_post or publish_post hooks.
Here is the code
function catch_that_image($post_id) {
    if(is_single()){
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  $first_img = $matches [1] [0];
  if(empty($first_img)){ //Defines a default image
    $first_img = "https://images.arabicpdfs.com/المكتبة-المفتوحة.jpg";
  }
  //return $first_img;
if ( has_post_thumbnail() ) {
            return;
        }
    else{       
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        $url     =$first_img;
        $desc    = "image description";
        $post_id =$post->ID;
        $image = media_sideload_image( $url, $post_id, $desc,'id' );
        set_post_thumbnail( $post_id, $image );
        //echo $post_id;
 } 
}}
add_action( 'publish_post', 'catch_that_image', 10, 1);
I could not figure out what I am missing
 
                        
The function
is_singledoes not work in this hook (even with post id as parameter). According to documentation the hookpublish_postalready specifies that it is a post see here and therefore the if-statement is not necessary. The suffix_postdefines the post type for which the hook is valid.I would also pass the post as a parameter.
As an alternative I would recommend the
transition_post_statushook see here