WordPress 函数 wp_get_attachment_url_raw 源码解析

wp_get_attachment_url_raw 函数用于获取 WordPress 附件的原始 URL。本文将深入解析该函数的源码,帮助您理解其工作原理。

函数定义:

/**
 * Retrieve the raw attachment URL.
 *
 * @since 4.7.0
 *
 * @param int|WP_Post $attachment Attachment ID or object.
 * @return string|false Raw attachment URL or false on failure.
 */
function wp_get_attachment_url_raw( $attachment ) {
  $attachment = get_post( $attachment );
  if ( ! $attachment ) {
    return false;
  }

  $url = $attachment->guid;

  /**
   * Filters the raw attachment URL.
   *
   * @since 4.7.0
   *
   * @param string $url Raw attachment URL.
   * @param int    $attachment_id Attachment ID.
   */
  return apply_filters( 'wp_get_attachment_url_raw', $url, $attachment->ID );
}

参数:

  • $attachment: 附件 ID 或附件对象。

返回值:

  • 成功:返回原始附件 URL (字符串类型)。
  • 失败:返回 false

函数解析:

  1. 函数首先使用 get_post() 获取附件对象,如果未找到则返回 false
  2. 获取附件对象的 guid 属性作为原始附件 URL。
  3. 使用 apply_filters() 对 URL 应用 wp_get_attachment_url_raw 过滤器,允许开发者进行修改。
  4. 返回过滤后的 URL 或 false

总结:

wp_get_attachment_url_raw 函数提供了一种简单、可靠的方式来获取 WordPress 附件的原始 URL。通过理解其源码和过滤器应用,您可以灵活地控制附件 URL 的行为,满足不同的需求。

WordPress 函数 wp_get_attachment_url_raw 源码解析

原文地址: http://www.cveoy.top/t/topic/lhC1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录