Created
January 3, 2017 17:34
-
-
Save moshfiqur/914459e008a99914624e900e8a3fc113 to your computer and use it in GitHub Desktop.
Programmatically create wordpress post and add category/tags with them
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Guessing this script is placed in the root wordpress directory. | |
// If not, change the require_once statements script path accordingly. | |
require_once('wp-load.php'); | |
require_once('wp-admin/includes/taxonomy.php'); | |
// Connect to database and get data | |
$conn = new mysqli('localhost', 'username', 'password', 'databasename'); | |
if ($conn->connect_error) { | |
die('Connection failed'); | |
} | |
$result = $conn->query("SELECT title, content, category, tag FROM table"); | |
if ($result->num_rows > 0) { | |
while($row = $result->fetch_assoc()) { | |
$post = [ | |
'post_title' => $row['title'], | |
'post_content' => $row['content'], | |
'post_status' => 'publish', // or can be 'draft' | |
'post_author' => 1 // The default first user | |
]; | |
$post_id = wp_insert_post($post); | |
// Add the category name as category | |
wp_set_object_terms($post_id, $row['category'], 'category'); | |
// Add tag data as post tag | |
wp_set_object_terms($post_id, $row['tag'], 'post_tag'); | |
} | |
} | |
// Done. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment