Watermark featured image as soon as it is set on post edit page

I want to watermark featured image of specific category when featured image is set on post edit page. I made a small script which watermarks but how can I know that featured image has been set so that script function runs automatically before publishing the post?

Related posts

1 comment

  1. “Thumbnails” or “Featured” images are attachments with an entry in the $wpdb->postmeta table under the key _thumbnail_id. A couple of different action hooks run when entries are added to postmeta. I think that probably the one you want is updated_{$meta_type}_meta. In your case, updated_post_meta. Something like this:

    add_action(
      'updated_post_meta',
      function ($meta_id, $object_id, $meta_key, $_meta_value ) {
        if ('_thumbnail_id' == $meta_key) {
          // take a good look around
          // var_dump($meta_id, $object_id, $meta_key, $_meta_value );
          // die;
        }
      },
      1,4
    );
    

    Your script would run where that commented section is. I have no idea how that script works, but there are the WordPress components.

    In your pastebin code, which I trust you will be editing into the question as you should, you are using this code:

    $old_featured_image = wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) ); 
    

    $post is not set in your function. That line will fail. But you are going a long way around anyway. wp_get_attachment_url requires a thumbnail ID. That ID is passed into the filter as $_meta_value. That line only needs to be:

    $old_featured_image = wp_get_attachment_url( $_meta_value );
    

    I can’t swear the rest of the function will work after that change but I am always concerned when I see exec.

Comments are closed.