Skip to content

Instantly share code, notes, and snippets.

@imelgrat
Last active May 30, 2021 04:07
Show Gist options
  • Save imelgrat/bbc26d3d0724d29a8e0f7da5832e7767 to your computer and use it in GitHub Desktop.
Save imelgrat/bbc26d3d0724d29a8e0f7da5832e7767 to your computer and use it in GitHub Desktop.
Create posts in WordPress from data in a MySQL database. Full article at: http://imelgrat.me/wordpress/bulk-upload-custom-posts-wordpress/
<?php
// Create posts in WordPress from data in a MySQL database. Full article at: http://imelgrat.me/wordpress/bulk-upload-custom-posts-wordpress/
//Load WordPress functions and plug-ins. Put correct path for this file. This example assumes you're using it from a sub-folder of WordPress
require_once ('../wp-load.php');
$database['hostname'] = 'SERVER';
$database['username'] = 'USER';
$database['password'] = 'PASSWORD';
$database['database'] = 'DATABASE';
$mysql_link = mysqli_connect($database['hostname'], $database['username'], $database['password']);
mysqli_select_db($mysql_link, $database['database']);
mysqli_query($mysql_link, "SET NAMES UTF8");
mysqli_query($mysql_link, "SET NAMES 'UTF8'");
mysqli_query($mysql_link, "SET CHARACTER SET UTF8");
/*
--
-- Table structure for table `products`
--
CREATE TABLE IF NOT EXISTS `products` (
`product_id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`description` text NOT NULL,
`price` float NOT NULL,
`ingredients` text NOT NULL,
PRIMARY KEY (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
*/
$query = "SELECT * FROM `products` WHERE `proccessed`= 0 ORDER BY `products`.`id` ASC;"; // products
$result = mysqli_query($mysql_link, $query);
while ($row = mysqli_fetch_assoc($result))
{
// Insert the post and set the category. See https://gist.github.com/imelgrat/46da054bc27d10dbdff5408502623b2d for custom post type declaration
$post_id = wp_insert_post(array(
'post_type' => 'product',
'post_title' => $row['name'],
'post_content' => $row['description'],
'post_status' => 'publish', // Can be draft, pending or any other post status
'comment_status' => 'closed', // if you prefer
'ping_status' => 'closed', // if you prefer
));
if ($post_id)
{
// Insert post meta (ACF Custom Fields)
add_post_meta($post_id, 'price', $row['price']);
add_post_meta($post_id, 'ingredients', $row['ingredients']);
}
echo $row['name'].' posted<br>';
}
?>
@RetroGameTalk
Copy link

It says "Insert the post and set the category" but it doesn't set the category, is it needed or not?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment