Categories
WordPress

HOW TO INSERT POST PROGRAMMATICALLY IN WORDPRESS?

Today I provide you with something quite different than normal, going to programmatically insert category and publish/page into WordPress. Everyone knows that WordPress may be the large community of users dealing with a large number of plugins and modifications to enhance it.

Sometimes,Its likely you need to add content programmatically in wordpress. WordPress has functions say wordpress_insert_publish to insert publish content and wordpress_insert_term to insert category in wordpress.

Learn More: HOW TO SET WORD LIMIT ON THE_CONTENT() IN WORDPRESS

Here, I will produce the function which see if a category exists or otherwise. Otherwise, wp_insert_term function can create new category. Within this function, you are able to pass parent category id too.

WooCommerce the best solution for eCommerce in 2020

function wp_create_term_wtc( $name, $taxonomy, $parent='' , $term_slug='') {

     $term_id = term_exists( $name, $taxonomy);

     if ( !$term_id )        
     $term_id = wp_insert_term( $name, $taxonomy,array('parent'=>$parent,'slug'=>$term_slug) );
     
     return $term_id;

}
create_term( 'wp_create_term_wtc','category');

Now, here’s about wp_insert_post function that will insert the publish into WordPress.Within function, you are able to pass publish_type is really a publish, page or any custom publish type.

function wtc_create_post( $title, $post_content, $post_status, $post_type, $post_slug ){
    
    // If the post/page doesn't already exist, then create it
    if( null == get_page_by_title( $title ) ) {
        $post_data = array(
                        'post_title' => $title,
                        'post_content' => $post_content,
                        'post_status' => $post_status,
                        'post_type' => $post_type,
                        'post_name' => $post_slug
                    );

    // Set the page ID so that we know the page was created successfully
    $last_id = wp_insert_post( $post_data );

}

That’s about this. I wish to say an enormous thanks to WordPress which supplies such type of function that is very helpful to all of us. I know someone available has been doing this already, but hopefully it can help someone out.

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

By Ankit Panchal

I'm a WordPress consultant and Web developer. I like solving digital problems which help your business grow. I specialize in WordPress plugin development and frontend development and am available for hire.