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.
1 2 3 4 5 6 7 8 9 10 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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.