Back to Top

How to insert Post Programmatically in WordPress?

Programmatically Insert Content in Wordpress

Today I bring you something a little different than usual, about to programmatically insert category and post/page into WordPress.We all know that WordPress is the large community of users working with thousands of plugins and modifications to improve it.

Sometimes,Its possible you want to add content programmatically in wordpress. WordPress has functions say wp_insert_post to insert post content and wp_insert_term to insert category in wordpress.

Here, I am going to create the function which check if a category exists or not. If not,wp_insert_term function will create new category.In this function, you can pass parent category id too.

function insert_term( $name, $tax,$parent='' ,$slug='') {
	$term_id = term_exists( $name, $tax ); //$tax = ‘category’
	if ( !$term_id )
		$term_id = wp_insert_term( $name, $tax,array('parent'=>$parent,'slug'=>$ludg) );
	return $term_id;
}

insert_term('bhumi','category');

Now, here is about wp_insert_post function which will insert the post into WordPress.Here in function, you can pass post_type is a post, page or any custom post type.

function insert_post($title,$post_content,$status,$post_type,$slug){
	// If the post/page doesn't already exist, then create it
	if( null == get_page_by_title( $title ) ) {
		$new_post = array(
					'post_title' => $title,
					'post_content' => $post_content,
					'post_status' => $status,
					'post_type' => $post_type,
					'post_name' =>$slug
					);
	// Set the page ID so that we know the page was created successfully
	$post_id = wp_insert_post($new_post');
}

That’s about it. I want to say a huge thank you to WordPress which provides such kind of function which is very useful to us.I’m sure someone out there has done this already, but hopefully it will help someone out.

A big thank you for reading and feel free to share your thoughts! Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts

How to create Custom regions in Drupal

Posted on 6 years ago

Bhumi

MySQL coalesce() function

Posted on 7 years ago

Bhumi

To prevent caching in web browser

Posted on 7 years ago

Bhumi

The Reader’s Poll – June 2015

Posted on 3 years ago

Bhumi

The Reader’s Poll – August 2014

Posted on 4 years ago

Bhumi

The Reader’s Poll – June 2014

Posted on 4 years ago

Bhumi

The Readers’ Poll – May 2014

Posted on 4 years ago

Bhumi

The Readers’ Poll – August 2013

Posted on 5 years ago

Bhumi