Posts – How to create categories with wp_insert_post and post_category

I am trying to create a post with PHP and its wordpress functions.

I’m using wp_insert_post(), but I can’t assign or create a custom category type of text for the post

I have this code:

require_once 'wp-load.php';
// This is test snippet for learning purposes.
// Creates a WordPress Post with code.
$post_id = -1;
// Set the Author, Slug, title and content of the new post

$category=get_cat_ID( 'Samsung' );
$author_id = 1;
$slug = 'wordpress-post-created-with-code';
$title="WordPress post created whith code";
$content="This is the content of the post that we are creating right now with code. 
            More text: I motsetning til hva mange tror, er ikke Lorem Ipsum bare tilfeldig tekst. 
            ";
$post_id = wp_insert_post(
    array(
        'comment_status'    =>  'closed',
        'post_category'     =>  array($category),
        'post_author'       =>  $author_id,
        'post_name'         =>  $slug,
        'post_title'        =>  $title,
        'post_content'      =>  $content,
        'post_status'       =>  'publish',
        'post_type'         =>  'post'


    )


);

As you can see I can’t specify category “Samsung” and if there is no category then create it Any idea how to do this? Thank You

Leave a Comment