Skip to content
Advertisement

WordPress: how to hook get_the_post_thumbnail_url() function

I’m new to WordPress. What I am trying to do is to hook the get_the_post_thumbnail_url() and return slightly different URL. I know that I can use WP add_action() for hooking. If I write my function and return required string how can I make sure that the get_the_post_thumbnail_url() will return my customized code?

Advertisement

Answer

get_the_post_thumbnail_url in wp-includes/post-thumbnail-template.php has no hooks or actions, it’s defined as follows:

function get_the_post_thumbnail_url( $post = null, $size = 'post-thumbnail' ) {
  $post_thumbnail_id = get_post_thumbnail_id( $post );
  if ( ! $post_thumbnail_id ) {
    return false;
  }
  return wp_get_attachment_image_url( $post_thumbnail_id, $size );
}

If you follow the wp_get_attachment_image_url function you find it uses the wp_get_attachment_image_src function which DOES apply filters so you are able to create a filter for it using wp_get_attachment_image_src

That will be your only way to interact with that function, albeit a little further up the functionality tree.

Usage instructions are as follows:

/**
     * Filters the image src result.
     *
     * @since 4.3.0
     *
     * @param array|false  $image         Either array with src, width & height, icon src, or false.
     * @param int          $attachment_id Image attachment ID.
     * @param string|array $size          Size of image. Image size or array of width and height values
     *                                    (in that order). Default 'thumbnail'.
     * @param bool         $icon          Whether the image should be treated as an icon. Default false.
     */
    apply_filters( 'wp_get_attachment_image_src', $image, $attachment_id, $size, $icon );
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement