Create New Post via PHP including External Feature Image in WordPress
As a WordPress developer, there may be times when you need to create new posts programmatically, rather than manually through the WordPress admin dashboard. This could be useful for tasks such as importing content from external sources, automating the publication of time-sensitive articles, or integrating WordPress with other applications.
In this blog post, we'll explore how to create a new WordPress post using PHP, and how to include an external feature image for the post. We'll walk through the code step-by-step, explaining each part of the process.
Prerequisites
Before we begin, make sure you have the following:
- A WordPress website with the necessary permissions to create posts and upload media
- PHP knowledge and the ability to write and execute PHP code
Step 1: Prepare the Image Data
The first step is to prepare the image data that you want to use as the featured image for the new post. In this example, we'll be using an image from the WordPress.org website, but you can substitute any image URL that you have access to.
$image_url = '';
$image_name = 'wp-header-logo.png';
$upload_dir = wp_upload_dir(); // Set upload folder
$image_data = file_get_contents($image_url); // Get image data
$unique_file_name = wp_unique_filename($upload_dir['path'], $image_name);
// Generate unique name
$filename = basename($unique_file_name); // Create image file name
In this code, we first define the URL of the image we want to use and the name we want to give the file. We then use the wp_upload_dir()
function to get the current upload directory for the WordPress site, and use file_get_contents()
to retrieve the image data from the URL.
Finally, we generate a unique file name for the image using the wp_unique_filename()
function, and extract the base name of the file.
Step 2: Save the Image to the Media Library
Now that we have the image data, we need to save it to the WordPress media library. We'll do this by checking the permissions of the upload directory and then creating the file on the server.
// Check folder permission and define file location
if (wp_mkdir_p($upload_dir['path'])) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
// Create the image file on the server
file_put_contents($file, $image_data);
// Check image file type
$wp_filetype = wp_check_filetype($filename, null);
// Set attachment data
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
// Create the attachment
$attach_id = wp_insert_attachment($attachment, $file, $post_id);
// Include image.php
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Define attachment metadata
$attach_data = wp_generate_attachment_metadata($attach_id, $file);
// Assign metadata to attachment
wp_update_attachment_metadata($attach_id, $attach_data);
In this section of the code, we first check the permissions of the upload directory using wp_mkdir_p()
. If the directory is writable, we create the file in the upload path. Otherwise, we create the file in the base directory of the WordPress installation.
We then use file_put_contents()
to save the image data to the file on the server. Next, we check the file type using wp_check_filetype()
and set the attachment data, including the post mime type, title, content, and status.
We then use the wp_insert_attachment()
function to create the attachment in the WordPress media library, and include the image.php
file to access the necessary image-related functions. Finally, we define the attachment metadata using wp_generate_attachment_metadata()
and assign it to the attachment using wp_update_attachment_metadata()
.
Step 3: Create the New Post
Now that we have the featured image set up, we can create the new post. Here's the code to do that:
// Set post data
$post_data = array(
'post_title' => 'New Post via PHP',
'post_content' => 'This is a new post created programmatically using PHP.',
'post_status' => 'publish',
'post_type' => 'post',
'post_author' => 1, // Replace with the ID of the author
'post_category' => array(1) // Replace with the ID of the category
);
// Create the post
$post_id = wp_insert_post($post_data);
// Assign the featured image to the post
set_post_thumbnail($post_id, $attach_id);
In this section, we first define the post data, including the title, content, status, type, author, and category. You can customize these values to fit your needs.
We then use the wp_insert_post()
function to create the new post, which returns the ID of the newly created post.
Finally, we use the set_post_thumbnail()
function to assign the featured image (the attachment we created earlier) to the new post.
Putting it All Together
Here's the complete code snippet that combines all the steps we've covered:
// Add Featured Image to Post
$image_url = ''; // Define the image URL here
$image_name = 'wp-header-logo.png';
$upload_dir = wp_upload_dir(); // Set upload folder
$image_data = file_get_contents($image_url); // Get image data
$unique_file_name = wp_unique_filename($upload_dir['path'], $image_name);
// Generate unique name
$filename = basename($unique_file_name); // Create image file name
// Check folder permission and define file location
if (wp_mkdir_p($upload_dir['path'])) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
// Create the image file on the server
file_put_contents($file, $image_data);
// Check image file type
$wp_filetype = wp_check_filetype($filename, null);
// Set attachment data
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
// Create the attachment
$attach_id = wp_insert_attachment($attachment, $file, $post_id);
// Include image.php
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Define attachment metadata
$attach_data = wp_generate_attachment_metadata($attach_id, $file);
// Assign metadata to attachment
wp_update_attachment_metadata($attach_id, $attach_data);
// Set post data
$post_data = array(
'post_title' => 'New Post via PHP',
'post_content' => 'This is a new post created programmatically using PHP.',
'post_status' => 'publish',
'post_type' => 'post',
'post_author' => 1, // Replace with the ID of the author
'post_category' => array(1) // Replace with the ID of the category
);
// Create the post
$post_id = wp_insert_post($post_data);
// Assign the featured image to the post
set_post_thumbnail($post_id, $attach_id);
This code will create a new WordPress post with an external image set as the featured image. You can customize the post data, image URL, and other parameters to fit your specific needs.
By automating the process of creating new posts and setting featured images, you can streamline your content management workflow and save valuable time. This technique can be particularly useful for scenarios where you need to publish content on a regular basis or integrate WordPress with other applications.
If you're interested in further enhancing your WordPress development skills, consider exploring the Flowpoint.ai web analytics platform. Flowpoint can help you identify technical issues and user experience problems that may be impacting your website's conversion rates, and provide data-driven recommendations to improve your site's performance
Get a Free AI Website Audit
Automatically identify UX and content issues affecting your conversion rates with Flowpoint's comprehensive AI-driven website audit.