WordPress is a flexible CMS and allows to manage a large number of posts that doesn’t limit users to regular “posts” and “pages” types of content through the use of custom posts.
WordPress also has built-in post import tools using RSS feeds, Tumbler, Blogger and several other sources. Other sources, such as Excel or CSV files, are also used after installing plug-ins.
However, in many situations it’s necessary to create posts from other sources, such as raw data stored in a MySQL database. In that case, it’s simpler to create a customized import script. When combined with custom post types, this provides a very powerful tool.
This article describes how to create a custom “product” post type and create posts using a PHP script and MySQL database as the content source.
Creating a WordPress custom post type
Before adding products to WordPress, it’s necessary to create a new custom-post type. In this case, I called it “product” but it can be anything you want. Here, we declare the posts’ CMS labels and configuration settings.
Adding custom fields (optional)
Although it is possible to place all the information about a product in the content section of the post, we can also create custom fields to do that. Using custom fields has the advantage making it much simpler to search using them as filters or sorting posts using them as sorting keys.
While there are many ways to manage customs fields (WordPress also has native functions to do it), I used Advanced Custom Fields (ACF), one of the best (if not the best) plug-ins for this task. Here, I added a price field and on for entering the product’s ingredients. Of course, it can be anything you want or none at all if your posts don’t require additional data fields.
Database structure and loading
For this example, I prepared a simple database structure but it can be as complex as you need. After creating the table, we can import data using CSV files, SQL from other tables, even typed into the table (it would defeat the purpose of automating the process but it is a valid option). Here’s the table layout I created using phpMyAdmin.
Creating the posts
Once we created the custom post type and loaded all the data into the database, we can start creating the posts on WordPress using its API. The script below gets rows from the “products” table and using a wp_insert_post() from the WP API, posts are created.
Optionally, we can use add_post_meta() to add extra, custom fields (ACF’s update_field() function can also be used but this example works even if ACF is not being used). The post creation script looks like something like this.
This article explains a much-simplified process for automatically creating WordPress posts using a database (MySQL in this case) as its content source. It can be enhanced in many ways but the main intent was to show the necessary steps to automate content creation using WP’s API.