skip to Main Content

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

2

Answers


  1. The function is_single does not work in this hook (even with post id as parameter). According to documentation the hook publish_post already specifies that it is a post see here and therefore the if-statement is not necessary. The suffix _post defines the post type for which the hook is valid.

    I would also pass the post as a parameter.

    function catch_that_image($post_id, $post)
    {
        ...
    }
    
    add_action('publish_post', 'catch_that_image', 10, 2);
    

    As an alternative I would recommend the transition_post_status hook see here

    Login or Signup to reply.
  2. I would recommend you the hook transition_post_status

    function custom_transition_post_status($new_status, $old_status, $post)
    {
        // here you can do your action something like this
        if(is_single() && $post->post_type == 'post') {
          ...
        }
    }
    
    add_action('transition_post_status', 'custom_transition_post_status', 10, 3);
    

    The insert or update should be done with the function wp_insert_post. Add the field ID if you want do update your post.

    $postData = [
            'post_title' => 'your title',
            'post_status' => 'publish',
            'post_type' => 'post'
    ];
    
    $postId = wp_insert_post($postData);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search