函数文档

_fix_attachment_links()

💡 云策文档标注

概述

_fix_attachment_links() 是一个 WordPress 内部函数,用于更新文章内容中附件链接的 href 属性,将其替换为最新的固定链接。它主要处理包含特定查询字符串的附件锚点链接。

关键要点

  • 函数接受一个参数:$post,可以是文章 ID 或 WP_Post 对象,用于指定要处理的文章。
  • 返回值类型多样:无更新时返回 void;更新失败时返回 0 或 WP_Error;更新成功时返回文章 ID。
  • 函数仅在启用固定链接且文章状态为 publish、future 或 private 时执行。
  • 通过正则表达式匹配内容中的链接,检查是否包含 '?attachment_id=' 和 'wp-att-' 模式,并验证 URL 和 rel 属性中的附件 ID 是否一致。
  • 使用 get_attachment_link() 获取附件的最新固定链接,并更新文章内容。
  • 更新操作通过 wp_update_post() 完成,涉及数据转义处理。

代码示例

function _fix_attachment_links( $post ) {
    $post    = get_post( $post, ARRAY_A );
    $content = $post['post_content'];

    // Don't run if no pretty permalinks or post is not published, scheduled, or privately published.
    if ( ! get_option( 'permalink_structure' ) || ! in_array( $post['post_status'], array( 'publish', 'future', 'private' ), true ) ) {
        return;
    }

    // Short if there aren't any links or no '?attachment_id=' strings (strpos cannot be zero).
    if ( ! strpos( $content, '?attachment_id=' ) || ! preg_match_all( '/]+)>[sS]+?/', $content, $link_matches ) ) {
        return;
    }

    $site_url = get_bloginfo( 'url' );
    $site_url = substr( $site_url, (int) strpos( $site_url, '://' ) ); // Remove the http(s).
    $replace  = '';

    foreach ( $link_matches[1] as $key => $value ) {
        if ( ! strpos( $value, '?attachment_id=' ) || ! strpos( $value, 'wp-att-' )
            || ! preg_match( '/href=(["'])[^"']*?attachment_id=(d+)[^"']*\1/', $value, $url_match )
            || ! preg_match( '/rel=["'][^"']*wp-att-(d+)/', $value, $rel_match ) ) {
                continue;
        }

        $quote  = $url_match[1]; // The quote (single or double).
        $url_id = (int) $url_match[2];
        $rel_id = (int) $rel_match[1];

        if ( ! $url_id || ! $rel_id || $url_id !== $rel_id || ! str_contains( $url_match[0], $site_url ) ) {
            continue;
        }

        $link    = $link_matches[0][ $key ];
        $replace = str_replace( $url_match[0], 'href=' . $quote . get_attachment_link( $url_id ) . $quote, $link );

        $content = str_replace( $link, $replace, $content );
    }

    if ( $replace ) {
        $post['post_content'] = $content;
        // Escape data pulled from DB.
        $post = add_magic_quotes( $post );

        return wp_update_post( $post );
    }
}

注意事项

  • 函数是内部函数,通常由 WordPress 核心调用,如 wp_write_post() 和 edit_post(),不建议在插件或主题中直接使用。
  • 依赖多个 WordPress 函数,如 get_option()、get_attachment_link() 和 wp_update_post(),需确保这些函数可用。
  • 自 WordPress 2.3.0 版本引入,使用时需考虑版本兼容性。

📄 原文内容

Replaces hrefs of attachment anchors with up-to-date permalinks.

Parameters

$postint|WP_Postrequired
Post ID or post object.

Return

void|int|WP_Error Void if nothing fixed. 0 or WP_Error on update failure. The post ID on update success.

Source

function _fix_attachment_links( $post ) {
	$post    = get_post( $post, ARRAY_A );
	$content = $post['post_content'];

	// Don't run if no pretty permalinks or post is not published, scheduled, or privately published.
	if ( ! get_option( 'permalink_structure' ) || ! in_array( $post['post_status'], array( 'publish', 'future', 'private' ), true ) ) {
		return;
	}

	// Short if there aren't any links or no '?attachment_id=' strings (strpos cannot be zero).
	if ( ! strpos( $content, '?attachment_id=' ) || ! preg_match_all( '/<a ([^>]+)>[sS]+?</a>/', $content, $link_matches ) ) {
		return;
	}

	$site_url = get_bloginfo( 'url' );
	$site_url = substr( $site_url, (int) strpos( $site_url, '://' ) ); // Remove the http(s).
	$replace  = '';

	foreach ( $link_matches[1] as $key => $value ) {
		if ( ! strpos( $value, '?attachment_id=' ) || ! strpos( $value, 'wp-att-' )
			|| ! preg_match( '/href=(["'])[^"']*?attachment_id=(d+)[^"']*\1/', $value, $url_match )
			|| ! preg_match( '/rel=["'][^"']*wp-att-(d+)/', $value, $rel_match ) ) {
				continue;
		}

		$quote  = $url_match[1]; // The quote (single or double).
		$url_id = (int) $url_match[2];
		$rel_id = (int) $rel_match[1];

		if ( ! $url_id || ! $rel_id || $url_id !== $rel_id || ! str_contains( $url_match[0], $site_url ) ) {
			continue;
		}

		$link    = $link_matches[0][ $key ];
		$replace = str_replace( $url_match[0], 'href=' . $quote . get_attachment_link( $url_id ) . $quote, $link );

		$content = str_replace( $link, $replace, $content );
	}

	if ( $replace ) {
		$post['post_content'] = $content;
		// Escape data pulled from DB.
		$post = add_magic_quotes( $post );

		return wp_update_post( $post );
	}
}

Changelog

Version Description
2.3.0 Introduced.