Using WordPress ‘begin_fetch_post_thumbnail_html’ PHP action

The begin_fetch_post_thumbnail_html WordPress PHP action fires before fetching the post thumbnail HTML and provides “just in time” filtering of all filters in wp_get_attachment_image().

Usage

add_action('begin_fetch_post_thumbnail_html', 'your_custom_function', 10, 3);

function your_custom_function($post_id, $post_thumbnail_id, $size) {
  // your custom code here

  return $post_id;
}

Parameters

  • $post_id (int): The post ID.
  • $post_thumbnail_id (int): The post thumbnail ID.
  • $size (string|int[]): Requested image size. Can be any registered image size name, or an array of width and height values in pixels (in that order).

More information

See WordPress Developer Resources: begin_fetch_post_thumbnail_html

Examples

Log Post Thumbnail Fetch

Log each time a post thumbnail is fetched:

add_action('begin_fetch_post_thumbnail_html', 'log_post_thumbnail_fetch', 10, 3);

function log_post_thumbnail_fetch($post_id, $post_thumbnail_id, $size) {
  error_log("Fetching post thumbnail for post ID: {$post_id}, Thumbnail ID: {$post_thumbnail_id}, Size: " . print_r($size, true));
  return $post_id;
}

Set Default Thumbnail Size

Set a default thumbnail size if no size is specified:

add_action('begin_fetch_post_thumbnail_html', 'set_default_thumbnail_size', 10, 3);

function set_default_thumbnail_size($post_id, $post_thumbnail_id, &$size) {
  if (empty($size)) {
    $size = 'medium';
  }
  return $post_id;
}

Increase Thumbnail Size

Increase the size of the thumbnail by a factor:

add_action('begin_fetch_post_thumbnail_html', 'increase_thumbnail_size', 10, 3);

function increase_thumbnail_size($post_id, $post_thumbnail_id, &$size) {
  if (is_array($size)) {
    $size[0] = $size[0] * 1.5;
    $size[1] = $size[1] * 1.5;
  }
  return $post_id;
}

Change Thumbnail ID

Change the thumbnail ID to a different attachment:

add_action('begin_fetch_post_thumbnail_html', 'change_thumbnail_id', 10, 3);

function change_thumbnail_id($post_id, &$post_thumbnail_id, $size) {
  $new_attachment_id = 123; // Replace with a valid attachment ID
  $post_thumbnail_id = $new_attachment_id;
  return $post_id;
}

Skip Fetching Thumbnails for Specific Post Types

Skip fetching thumbnails for specific post types:

add_action('begin_fetch_post_thumbnail_html', 'skip_thumbnail_fetch_for_post_types', 10, 3);

function skip_thumbnail_fetch_for_post_types($post_id, $post_thumbnail_id, $size) {
  $post_type = get_post_type($post_id);
  $skip_post_types = array('custom_post_type'); // Replace with your desired post types to skip

  if (in_array($post_type, $skip_post_types)) {
    return false;
  }

  return $post_id;
}