_delete_attachment_theme_mod()
云策文档标注
概述
_delete_attachment_theme_mod() 是一个 WordPress 函数,用于在删除附件时检查其是否为页眉、背景或自定义徽标图像,并相应地移除相关的主题修改或选项。
关键要点
- 函数检查附件 ID 是否与当前设置的页眉图像、背景图像、自定义徽标或站点徽标匹配。
- 如果匹配,则使用 remove_theme_mod() 或 delete_option() 移除对应的主题修改或选项,防止引用已删除的附件。
- 函数处理多种图像类型,包括自定义徽标(custom_logo)、站点徽标(site_logo)、页眉图像(header_image)和背景图像(background_image)。
代码示例
function _delete_attachment_theme_mod( $id ) {
$attachment_image = wp_get_attachment_url( $id );
$header_image = get_header_image();
$background_image = get_background_image();
$custom_logo_id = (int) get_theme_mod( 'custom_logo' );
$site_logo_id = (int) get_option( 'site_logo' );
if ( $custom_logo_id && $custom_logo_id === $id ) {
remove_theme_mod( 'custom_logo' );
remove_theme_mod( 'header_text' );
}
if ( $site_logo_id && $site_logo_id === $id ) {
delete_option( 'site_logo' );
}
if ( $header_image && $header_image === $attachment_image ) {
remove_theme_mod( 'header_image' );
remove_theme_mod( 'header_image_data' );
}
if ( $background_image && $background_image === $attachment_image ) {
remove_theme_mod( 'background_image' );
}
}注意事项
- 此函数通常由 WordPress 核心在删除附件时自动调用,开发者无需直接使用,但应了解其机制以避免主题设置错误。
- 函数依赖于其他函数如 wp_get_attachment_url() 和 get_theme_mod(),确保这些函数正常工作以正确执行检查。
- 从版本 6.6.0 起,函数还处理站点徽标选项,反映了 WordPress 功能的更新。
原文内容
Checks an attachment being deleted to see if it’s a header or background image.
Description
If true it removes the theme modification which would be pointing at the deleted attachment.
Parameters
$idintrequired-
The attachment ID.
Source
function _delete_attachment_theme_mod( $id ) {
$attachment_image = wp_get_attachment_url( $id );
$header_image = get_header_image();
$background_image = get_background_image();
$custom_logo_id = (int) get_theme_mod( 'custom_logo' );
$site_logo_id = (int) get_option( 'site_logo' );
if ( $custom_logo_id && $custom_logo_id === $id ) {
remove_theme_mod( 'custom_logo' );
remove_theme_mod( 'header_text' );
}
if ( $site_logo_id && $site_logo_id === $id ) {
delete_option( 'site_logo' );
}
if ( $header_image && $header_image === $attachment_image ) {
remove_theme_mod( 'header_image' );
remove_theme_mod( 'header_image_data' );
}
if ( $background_image && $background_image === $attachment_image ) {
remove_theme_mod( 'background_image' );
}
}