✨专业 WordPress 开发,定制建站,高效上线,合作即享优化服务!🚀
实现 WordPress 特色图(Featured Image)不仅可以上传本地图片,还能支持直接使用外部 URL(站外地址)作为特色图。WordPress 默认只支持本地上传,所以需要自定义一些功能。下面我给你提供一个完整实现方案(添加后台输入框 + 前端支持显示外部图片):
把下面代码加到主题 functions.php 或自定义插件里:
// 添加特色图外部 URL 输入框
function add_external_featured_image_meta_box() {
add_meta_box(
'external_featured_image',
__('外部特色图 URL', 'textdomain'),
'render_external_featured_image_meta_box',
['post', 'page'], // 可改为自定义文章类型
'side',
'low'
);
}
add_action('add_meta_boxes', 'add_external_featured_image_meta_box');
function render_external_featured_image_meta_box($post) {
wp_nonce_field('save_external_featured_image', 'external_featured_image_nonce');
$value = get_post_meta($post->ID, '_external_featured_image', true);
echo '<input type="url" style="width:100%;" name="external_featured_image" value="' . esc_attr($value) . '" placeholder="https://example.com/image.jpg">';
}
// 保存外部特色图 URL
function save_external_featured_image_meta_box($post_id) {
if (!isset($_POST['external_featured_image_nonce']) || !wp_verify_nonce($_POST['external_featured_image_nonce'], 'save_external_featured_image')) {
return;
}
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
if (isset($_POST['external_featured_image'])) {
$url = esc_url_raw($_POST['external_featured_image']);
update_post_meta($post_id, '_external_featured_image', $url);
}
}
add_action('save_post', 'save_external_featured_image_meta_box');
功能说明:
-
在文章编辑页右侧“特色图”下方会出现一个输入框
-
可以输入站外图片 URL
-
保存文章时会存入
_external_featured_image元数据
2️⃣ 前端输出特色图时优先使用外部 URL
替换主题中调用 get_the_post_thumbnail() 的地方,改为:
function get_featured_image_or_external($post_id = null, $size = 'post-thumbnail', $attr = []) {
if (!$post_id) $post_id = get_the_ID();
// 先获取外部 URL
$external_url = get_post_meta($post_id, '_external_featured_image', true);
if ($external_url) {
return '<img src="' . esc_url($external_url) . '" class="wp-post-image" />';
}
// 没有外部 URL 则返回本地特色图
if (has_post_thumbnail($post_id)) {
return get_the_post_thumbnail($post_id, $size, $attr);
}
return ''; // 没有特色图
}
在模板里使用:
优化版可以参考这边文章:优化版WordPress 特色图框里可以上传或输入外部 URL,一体化管理

