在这里,在这个 functions.php 文件中,我想做的是从我的帖子内容中获取图像,实际上我正在内容中使用 image_url (获取第一张图像的这部分工作正常,我已经测试过它 ) 。问题是我无法使用 url 上传图像并将其设置为特色图像,从而弹出“发布失败”窗口。有人可以帮我吗,或者你有其他方法吗?
function generate_post_featured_image($post_ID) {
$post = get_post($post_ID);
if (empty($post->featured_image)) {
// Find the first image URL in the post content
preg_match('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
if (isset($matches[1])) {
$image_url = $matches[1];
// Sideload the image and get the attachment ID
$attachment_id = media_sideload_image($image_url, $post_ID, null, 'id');
if (!is_wp_error($attachment_id) && !empty($attachment_id)) {
// Set the attachment ID as the featured image
set_post_thumbnail($post_ID, $attachment_id);
} else {
$error_message = $attachment_id->get_error_message();
echo 'Error sideloading image: ' . $error_message;
}
}
}
}
add_action('publish_post', 'generate_post_featured_image');
function upload_image_and_set_featured($post_ID) {
$post = get_post($post_ID);
if (empty($post->featured_image)) {
// Find the first image URL in the post content
preg_match('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
if (isset($matches[1])) {
$image_url = $matches[1];
// Upload the image and get the attachment ID
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
if (wp_mkdir_p($upload_dir['path'])) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
file_put_contents($file, $image_data);
$wp_filetype = wp_check_filetype($filename, null);
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment($attachment, $file, $post_ID);
if (!is_wp_error($attachment_id)) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata($attachment_id, $file);
wp_update_attachment_metadata($attachment_id, $attachment_data);
set_post_thumbnail($post_ID, $attachment_id);
} else {
$error_message = $attachment_id->get_error_message();
echo 'Error uploading image: ' . $error_message;
}
}
}
}
add_action('publish_post', 'upload_image_and_set_featured');
将上述代码添加到您的function.php中。此代码从您的内容中获取第一张图像并将其设置在特色图像中。
if (isset($_FILES['fileToUpload']) && !empty($_FILES['fileToUpload']['name'])) {
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_id = media_handle_upload('fileToUpload', $post_id);
if (is_wp_error($attachment_id)) {
echo 'Error uploading image: ' . $attachment_id->get_error_message();
} else {
set_post_thumbnail($post_id, $attachment_id);
}
}
return $post_id ? '<p>Post created successfully!</p>' : '<p>Error creating post!</p>';