// 自动提取文章第一张图片作为特色图片 function nirvana_auto_featured_image($content) { global $post; if (has_post_thumbnail($post->ID)) { return $content; } if (preg_match('/]+src=["\']([^"\']+)["\']/i', $content, $matches)) { $image_url = $matches[1]; $image_id = attachment_url_to_postid($image_url); if ($image_id) { set_post_thumbnail($post->ID, $image_id); } } return $content; } add_filter('the_content', 'nirvana_auto_featured_image', 5); // 添加默认特色图片功能 function nirvana_default_featured_image($html, $post_id, $post_thumbnail_id, $size, $attr) { if (empty($html)) { $default_image = get_template_directory_uri() . '/assets/imgs/default-header.svg'; $html = 'Default Featured Image'; } return $html; } add_filter('post_thumbnail_html', 'nirvana_default_featured_image', 10, 5); // 修改 get_post_thumbnail_id 返回值,当没有特色图片时返回默认值 function nirvana_default_featured_image_id($thumbnail_id, $post_id) { if (empty($thumbnail_id)) { // 返回一个虚拟 ID,让 post_thumbnail_html 过滤器处理 return null; } return $thumbnail_id; } add_filter('get_post_thumbnail_id', 'nirvana_default_featured_image_id', 10, 2); // 修改 get_post_meta 返回,当日志头图为空时返回默认图片 function nirvana_default_head_img($value, $post_id, $meta_key, $single) { if ($meta_key === '日志头图' && empty($value)) { return get_template_directory_uri() . '/assets/imgs/default-header.svg'; } return $value; } add_filter('get_post_metadata', 'nirvana_default_head_img', 10, 4);