wordpress获取文章图片,自动更新特色图插件

<?php
/**
 * Plugin Name: Auto Set Featured Image On Cron
 * Plugin URI: https://www.yourwebsite.com/
 * Description: This plugin automatically sets the first image in a post as the featured image using a WordPress Cron Job.
 * Version: 1.0.0
 * Author: Your Name
 * Author URI: https://www.yourwebsite.com/
 */

// 自定义一个Cron时间间隔
function custom_cron_intervals($schedules) {
  $schedules['every_five_minutes'] = array(
    'interval' => 5 * 60, // 5 minutes in seconds
    'display'  => 'Every Five Minutes',
  );
  return $schedules;
}
add_filter('cron_schedules', 'custom_cron_intervals');

// 在WordPress初始化时添加定时任务
function setup_cron_featured_image() {
  if (!wp_next_scheduled('set_featured_image_on_cron')) {
    wp_schedule_event(time(), 'every_five_minutes', 'set_featured_image_on_cron');
  }
}
add_action('init', 'setup_cron_featured_image');

// 当定时任务运行时,设置特色图像
function set_featured_image_on_cron() {
  // 获取最新发布的文章
  $args = array(
    'numberposts' => 1,
    'post_status' => 'publish'
  );
  $recent_posts = wp_get_recent_posts($args);

  if (count($recent_posts) == 0) {
    return;
  }

  $post_id = $recent_posts[0]['ID'];

  // 检查文章是否已经设置了特色图片
  if (has_post_thumbnail($post_id)) {
    return;
  }

    // 检查文章是否已经设置了特色图片
  if (has_post_thumbnail($post_id)) {
    return;
  }

    $post_content = get_post_field('post_content', $post_id);
    preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $post_content, $image);
    
    if (!isset($image['src'])) {
        error_log("Post ID {$post_id}: No image found in content.");
        return;
    }
    
    $featured_image = "https://www.qmwu.com" . $image['src'];
    //$featured_image = "https://www.qmwu.com/wp-content/uploads/20230423/67f292e397ddd533dab59d2eecd1a53a.jpg";



  $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);
    error_log("Post ID {$post_id}: Featured image set successfully.");
  } else {
    error_log("Post ID {$post_id}: Failed to set featured image.");
  }
}

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)) {
    error_log("Post ID {$post_id}: Error uploading image - " . $attachment_id->get_error_message());
    return false;
  }

  return $attachment_id;
}

add_action('set_featured_image_on_cron', 'set_featured_image_on_cron');
?>
© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享