<?php
/*
Plugin Name: a Hello World with Image Post
Description: Creates a post titled "你好" with a local image as content upon activation.
Version: 1.0
Author: Your Name
Author URI: http://yourwebsite.com
License: GPL2
*/
// Exit if accessed directly
if (!defined('ABSPATH')) {
exit;
}
// Hook into activation to create the post and upload the image
register_activation_hook(__FILE__, 'create_hello_world_post_with_image');
function create_hello_world_post_with_image() {
// Start output buffering to catch any output
ob_start();
// Define the local path to the image
$local_image_path = plugin_dir_path(__FILE__) . '1.jpg'; // Replace with your image's local path
// Check if the image file exists
if (!file_exists($local_image_path)) {
error_log('Hello World with Image Post: Image file not found.');
// End output buffering and discard any output
ob_end_clean();
return;
}
// Read the image into a variable
$image_content = file_get_contents($local_image_path);
// Create an array that looks like a $_FILES array
$image_array = array(
'name' => basename($local_image_path),
'type' => 'image/jpeg', // Replace with your image's mime type
'tmp_name' => $local_image_path,
'error' => 0,
'size' => filesize($local_image_path)
);
// Use the media_handle_sideload function to upload the image
$attachment_id = media_handle_sideload($image_array, 0);
// Check for errors and that the attachment was created successfully
if (is_wp_error($attachment_id)) {
error_log('Hello World with Image Post: ' . $attachment_id->get_error_message());
// End output buffering and discard any output
ob_end_clean();
return;
}
// Create the post
$post = array(
'post_title' => '你好',
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1, // Set the post author ID
'post_type' => 'post',
);
// Insert the post into the database
$post_id = wp_insert_post($post);
// Check if the post was created successfully
if (is_wp_error($post_id)) {
error_log('Hello World with Image Post: Failed to create post.');
// End output buffering and discard any output
ob_end_clean();
return;
}
// Update the post content with the image
$post_content = wp_get_attachment_image($attachment_id, 'thumbnail'); // Use the thumbnail size
$updated_post = array(
'ID' => $post_id,
'post_content' => $post_content,
);
wp_update_post($updated_post);
// End output buffering and discard any output
ob_end_clean();
}
?>