How to create a post in Wordpress through PHP.

If you regularly work with Wordpress, at some point of time you will definitely feel the need of a php script that creates a wordpress post for you. Here's a very simple script that will do the job for you.


Code:


<?php
require_once("wp-load.php");

$title = $_POST['title'];
$body = $_POST['body'];




global $user_ID;
$new_post = array(
'post_title' => $title,
'post_content' => $body,
'post_status' => 'publish',
'post_author' => "admin",
'post_type' => 'post',
'tags_input' => array("tags"),

);


$post_id = wp_insert_post($new_post);

echo 'Post created';

?>


Explanation:
This code has three parts.
The first part takes inputs from users through a post request. You can create a form in html to easily transfer data to this php snippet. The received data is then put into two variables title and body.

The second part of the code prepares an array with options. These options are used in the final insert post method. You can see how I have created the array. There are a lot more options available such as date, category etc which I will show you in the next post.

The third part of the code takes the array as its argument and  creates a new post. wp_insert_post($arg) is the function that is used to create a post.


Easy enough? In the next post, I'll add some more options like categories, date and featured images.

Lots of Love! :)

SHARE ON:

Hi! I'm Siddhant Minocha, a Jaipur based hacker/developer. I spend most of my day coding things, trying to develop the next billion dollar idea. When I'm not over-analyzing random stuff and people, I hang out with friends (mostly entrepreneurs). I'm in my final year of graduation and till now I have started and exited 3 startups and developed a lot of websites and software for different companies. Follow me on twitter and other social networks to see what I keep doing. You can also hire me to design/develop your website, if you're worried about your website or app's security or any other tech related work. See ya! :D

    Blogger Comment

0 comments:

Post a Comment