左右不逢缘 发表于 昨天 08:13

wordpress里更新文章如何自动摘取第一张图片作为缩略图特色图?

有没有人知道wordpress里更新文章如何自动摘取第一张图片作为缩略图/特色图?

Crystαl 发表于 昨天 08:14

/** * 自动设置文章的第一张图片为特色图片 */function auto_set_featured_image($post_id) {    // 排除自动保存、修订版本和非文章类型    if (      defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ||      wp_is_post_revision($post_id) ||      get_post_type($post_id) !== 'post'    ) {      return;    }    // 检查是否有现有特色图片    if (!has_post_thumbnail($post_id)) {      $post = get_post($post_id);      // 使用正则匹配第一张图片      preg_match('//i', $post->post_content, $matches);      if ($matches) {            $image_url = $matches;            $upload_dir = wp_upload_dir();            // 处理本地图片            if (strpos($image_url, $upload_dir['baseurl']) === 0) {                $attachment_id = attachment_url_to_postid($image_url);                if ($attachment_id) {                  set_post_thumbnail($post_id, $attachment_id);                  return;                }            }            // 处理远程图片            require_once(ABSPATH . 'wp-admin/includes/media.php');            require_once(ABSPATH . 'wp-admin/includes/file.php');            require_once(ABSPATH . 'wp-admin/includes/image.php');            try {                $tmp = download_url($image_url);                if (is_wp_error($tmp)) {                  @unlink($tmp);                  return;                }                $file_array = array(                  'name' => basename($image_url),                  'tmp_name' => $tmp                );                $attachment_id = media_handle_sideload($file_array, $post_id);                if (!is_wp_error($attachment_id)) {                  set_post_thumbnail($post_id, $attachment_id);                }                @unlink($tmp);            } catch (Exception $e) {                return;            }      }    }}add_action('save_post', 'auto_set_featured_image');添加到当前主题的 functions.php 文件中

Crystαl 发表于 昨天 08:15

基本主题都自带吧
页: [1]
查看完整版本: wordpress里更新文章如何自动摘取第一张图片作为缩略图特色图?