Skip to content

Instantly share code, notes, and snippets.

@milapdave
Forked from imelgrat/bulk-post-create.php
Created December 25, 2017 10:38
Show Gist options
  • Save milapdave/dabda9986b673a536dfc638a1654d5c6 to your computer and use it in GitHub Desktop.
Save milapdave/dabda9986b673a536dfc638a1654d5c6 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>';
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment