✨专业 WordPress 开发,定制建站,高效上线,合作即享优化服务!🚀
<?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">';
echo '<p style="font-size:12px;color:#666;">如果同时上传本地特色图,将优先显示外部 URL。</p>';
}
// 保存外部特色图 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)
function get_featured_image_or_external($post_id = null, $size = 'post-thumbnail', $attr = []) {
if (!$post_id) $post_id = get_the_ID();
$external_url = get_post_meta($post_id, '_external_featured_image', true);
if ($external_url) {
$class = isset($attr['class']) ? esc_attr($attr['class']) : 'wp-post-image';
$alt = get_the_title($post_id);
return '<img src="' . esc_url($external_url) . '" alt="' . esc_attr($alt) . '" class="' . $class . '">';
}
if (has_post_thumbnail($post_id)) {
return get_the_post_thumbnail($post_id, $size, $attr);
}
return ''; // 没有特色图
}
// 可选:在后台“特色图”框中显示外部 URL缩略图
function show_external_featured_image_preview($content, $post_id) {
$url = get_post_meta($post_id, '_external_featured_image', true);
if ($url && !has_post_thumbnail($post_id)) {
$content = '<img src="' . esc_url($url) . '" style="max-width:100%;display:block;margin-bottom:5px;">' . $content;
}
return $content;
}
add_filter('admin_post_thumbnail_html', 'show_external_featured_image_preview', 10, 2);
✅ 功能说明:
-
文章/页面编辑页右侧“特色图”下方出现输入框,可填站外图片 URL。
-
如果同时上传本地特色图,外部 URL 会优先显示。
-
前端模板中调用:
即可自动输出外部图或本地特色图。
4. 后台特色图框如果没有上传本地图,会显示外部图缩略图。

