WordPress:如何挂钩 get_the_post_thumbnail_url() 函数

Rom*_*man 2 php wordpress wordpress-hook

我是 WordPress 新手。我想做的是挂钩get_the_post_thumbnail_url()并返回略有不同的 URL。我知道我可以使用 WPadd_action()进行挂钩。如果我编写函数并返回所需的字符串,如何确保get_the_post_thumbnail_url()将返回我的自定义代码?

Ale*_*usa 5

wp-includes/post-thumbnail-template.php中的get_the_post_thumbnail_url没有钩子或操作,其定义如下:

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 );
}
Run Code Online (Sandbox Code Playgroud)

如果您遵循wp_get_attachment_image_url函数,您会发现它使用wp_get_attachment_image_src函数,该函数确实应用过滤器,因此您可以使用它为其创建过滤器wp_get_attachment_image_src

这将是您与该功能交互的唯一方式,尽管在功能树上稍靠前一些。

使用说明如下:

/**
     * 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 );
Run Code Online (Sandbox Code Playgroud)