方法如下:
1,首先在uploads目录当中新建一个名为default-featured-images的目录.
2,在当前主题函数文件functions.php当中结尾添加如下代码:
/**
* 自动设置文章特色图像
* 适用于 PHP 7.4+
*/
// 确保主题支持特色图像
if (!current_theme_supports('post-thumbnails')) {
add_theme_support('post-thumbnails');
}
/**
* 从文章内容中获取第一张有效的图片URL
* @param string $content 文章内容
* @return string|null 图片URL或null
*/
function get_first_valid_image($content) {
if (empty($content)) {
return null;
}
// 匹配所有图片标签
if (preg_match_all('/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $content, $matches)) {
foreach ($matches[1] as $image_url) {
// 排除表情符号、小图标等
if (strpos($image_url, 'emoji') !== false ||
strpos($image_url, 'icon') !== false ||
strpos($image_url, 'smilies') !== false) {
continue;
}
return esc_url($image_url);
}
}
return null;
}
/**
* 获取随机默认图片
* @return string|null 图片路径或null
*/
function get_random_default_image() {
static $default_images = null;
if ($default_images === null) {
$upload_dir = wp_upload_dir();
$default_images_path = trailingslashit($upload_dir['basedir']) . 'default-featured-images';
// 确保目录存在
if (!file_exists($default_images_path)) {
wp_mkdir_p($default_images_path);
return null;
}
// 获取所有图片文件
$default_images = glob($default_images_path . '/*.{jpg,jpeg,png,gif}', GLOB_BRACE) ?: [];
}
return !empty($default_images) ? $default_images[array_rand($default_images)] : null;
}
/**
* 处理并设置特色图像
* @param int $post_id 文章ID
* @param string $image_source 图片来源(URL或路径)
* @return bool 是否成功
*/
function process_and_set_thumbnail($post_id, $image_source) {
if (empty($image_source) || empty($post_id)) {
return false;
}
// 加载必要的文件
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
// 如果是URL,先下载
if (filter_var($image_source, FILTER_VALIDATE_URL)) {
$tmp = download_url($image_source);
if (is_wp_error($tmp)) {
return false;
}
$file_array = array(
'name' => sanitize_file_name(basename(parse_url($image_source, PHP_URL_PATH))),
'tmp_name' => $tmp
);
} else {
// 本地文件
$file_array = array(
'name' => sanitize_file_name(basename($image_source)),
'tmp_name' => $image_source
);
}
// 处理媒体文件
$image_id = media_handle_sideload($file_array, $post_id);
// 清理临时文件
if (isset($tmp)) {
@unlink($tmp);
}
if (is_wp_error($image_id)) {
return false;
}
return (bool)set_post_thumbnail($post_id, $image_id);
}
/**
* 自动设置特色图像
* @param int|WP_Post $post_id 文章ID或对象
* @return bool 是否成功
*/
function auto_set_featured_image($post_id) {
try {
// 获取文章ID
$post_id = ($post_id instanceof WP_Post) ? $post_id->ID : (int)$post_id;
// 基本检查
if (empty($post_id) ||
(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) ||
wp_is_post_revision($post_id) ||
!in_array(get_post_type($post_id), ['post', 'page'], true) ||
has_post_thumbnail($post_id)) {
return false;
}
// 获取文章内容
$post = get_post($post_id);
if (!$post) {
return false;
}
// 尝试从文章内容获取图片
$content_image = get_first_valid_image($post->post_content);
if ($content_image) {
// 检查是否是本地媒体库图片
$image_id = attachment_url_to_postid($content_image);
if ($image_id) {
return (bool)set_post_thumbnail($post_id, $image_id);
}
// 处理外部图片
if (process_and_set_thumbnail($post_id, $content_image)) {
return true;
}
}
// 使用随机默认图片
$random_image = get_random_default_image();
if ($random_image) {
return process_and_set_thumbnail($post_id, $random_image);
}
return false;
} catch (Exception $e) {
error_log('Auto Featured Image Error: ' . $e->getMessage());
return false;
}
}
/**
* 确保文章有特色图像
* @param mixed $post_id 文章ID或对象
*/
function ensure_featured_image($post_id = null) {
try {
// 处理不同类型的输入
if (is_null($post_id)) {
$post_id = get_the_ID();
} elseif (is_object($post_id)) {
$post_id = $post_id->ID;
}
if ($post_id && !has_post_thumbnail($post_id)) {
auto_set_featured_image($post_id);
}
} catch (Exception $e) {
error_log('Ensure Featured Image Error: ' . $e->getMessage());
}
}
// 注册各种钩子
add_action('save_post', 'auto_set_featured_image');
add_action('the_post', 'ensure_featured_image');
add_action('get_header', 'ensure_featured_image');
// 修改特色图像显示
add_filter('post_thumbnail_html', function($html, $post_id) {
try {
if (empty($html) && !empty($post_id)) {
ensure_featured_image($post_id);
$html = get_the_post_thumbnail($post_id, 'full');
}
return $html ?: '';
} catch (Exception $e) {
error_log('Thumbnail HTML Error: ' . $e->getMessage());
return $html;
}
}, 10, 2);
3,往default-featured-images的目录当中添加自己的图片(图片格式支持:jpg,jpeg,png,gif )就可以了.
说明:
如果文章特色图像没有自动获到这个指定目录当中的图片,请在wordpress当中编辑这个functions.php文件,随便在末尾空白处回车再”更新”就可以了.
评论抢沙发