Wordpress automatically sets the first picture of the article as the featured picture

// 在保存文章时设置特色图片
function set_featured_image_on_save_post($post_id) {
  // 检查文章类型是否为 post
  if ('post' !== get_post_type($post_id)) {
    return;
  }

  // 获取文章内容
  $post_content = get_post_field('post_content', $post_id);

  // 获取文章的第一张图片
  preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $post_content, $image);
  $featured_image = $image['src'];

  // 如果文章没有图片,则返回
  if (!$featured_image) {
    return;
  }

  // 将第一张图片设置为特色图片
  $attachment_id = attachment_url_to_postid($featured_image);
  if (!$attachment_id) {
    $attachment_id = upload_featured_image($featured_image, $post_id);
  }
  if ($attachment_id) {
    set_post_thumbnail($post_id, $attachment_id);
  }
}

// 将图片上传到媒体库并返回其附件 ID
function upload_featured_image($image_url, $post_id) {
  require_once(ABSPATH . 'wp-admin/includes/media.php');
  require_once(ABSPATH . 'wp-admin/includes/file.php');
  require_once(ABSPATH . 'wp-admin/includes/image.php');

  // 下载图片并将其上传到媒体库
  $image_name = basename($image_url);
  $image_tmp = download_url($image_url);
  $image_file = array(
    'name' => $image_name,
    'tmp_name' => $image_tmp
  );
  $attachment_id = media_handle_sideload($image_file, $post_id);

  // 如果上传失败,则返回
  if (is_wp_error($attachment_id)) {
    return false;
  }

  return $attachment_id;
}

// 添加保存文章时的钩子函数
add_action('save_post', 'set_featured_image_on_save_post');

Guess you like

Origin blog.csdn.net/qq_39339179/article/details/129812259