问题描述
我写了一个插件,为所有 non-set(空) 标题设置默认标题,并保留手动设置的标题 (non-empty) 。
问题是当我上传新照片 (到图库) 时,WordPress 默认将标题设置为文件名。如何禁用它并强制 WordPress 使用空字符串作为默认图像标题?
最佳解决方案
您可以尝试以下内容来清除图像附件的标题插入但未更新:
/**
* Empty the image attachment's title only when inserted not updated
*/
add_filter( 'wp_insert_attachment_data', function( $data, $postarr )
{
if(
empty( $postarr['ID'] )
&& isset( $postarr['post_mime_type'] )
&& wp_match_mime_types( 'image', $postarr['post_mime_type'] )
)
$data['post_title'] = '';
return $data;
}, 10, 2 );
在这里,如果附件的 ID
为空,并且 mime 类型是根据 wp_match_mime_types()
的图像类型,则使用 wp_insert_attachment_data
过滤器来覆盖附件的标题。一个简单的'image' === substr( $postarr['post_mime_type'], 0, 5 )
检查也可以工作。您甚至可以定位给定的 MIME 类型,如 image/jpeg
。
参考文献
注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。