钩子文档

wp_get_attachment_url

💡 云策文档标注

概述

wp_get_attachment_url 是一个 WordPress 过滤器,用于修改附件 URL。它常用于解决 HTTP/HTTPS 混合内容问题,避免浏览器警告。

关键要点

  • 过滤器名称:wp_get_attachment_url
  • 参数:$url(附件 URL 字符串)和 $attachment_id(附件文章 ID)
  • 主要用途:调整附件 URL,例如强制使用 HTTPS 以避免混合内容警告
  • 注意事项:wp_get_attachment_url() 函数本身不区分 HTTP 或 HTTPS 请求,需通过此过滤器手动处理

代码示例

add_filter('wp_get_attachment_url', 'honor_ssl_for_attachments');
function honor_ssl_for_attachments($url) {
    $http = site_url(FALSE, 'http');
    $https = site_url(FALSE, 'https');
    return ( $_SERVER['HTTPS'] == 'on' ) ? str_replace($http, $https, $url) : $url;
}

📄 原文内容

Filters the attachment URL.

Parameters

$urlstring
URL for the given attachment.
$attachment_idint
Attachment post ID.

More Information

wp_get_attachment_url() doesn’t distinguish whether a page request arrives via HTTP or HTTPS.

Using wp_get_attachment_url filter, we can fix this to avoid the dreaded mixed content browser warning:

add_filter('wp_get_attachment_url', 'honor_ssl_for_attachments');
function honor_ssl_for_attachments($url) {
	$http = site_url(FALSE, 'http');
	$https = site_url(FALSE, 'https');
	return ( $_SERVER['HTTPS'] == 'on' ) ? str_replace($http, $https, $url) : $url;
}

Source

$url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );

Changelog

Version Description
2.1.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    As of WordPress Version 3.2.1, wp_get_attachment_url() doesn’t distinguish whether a page request arrives via HTTP or HTTPS.

    Using wp_get_attachment_url filter, we can fix this to avoid the dreaded mixed content browser warning

    add_filter( 'wp_get_attachment_url', 'wpdocs_honor_ssl_for_attachments' );
    function wpdocs_honor_ssl_for_attachments( $url ) {
    	$http = site_url( FALSE, 'http' );
    	$https = site_url( FALSE, 'https' );
    	return ( 'on' === $_SERVER['HTTPS'] ) ? str_replace( $http, $https, $url ) : $url;
    }