0

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

I am using wp_insert_post () but I can not assign a custom category type text to the post nor create it

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 not assign the category "Samsung" and in case there is no category then create it Any idea how to do it? Thank you

0

In order to add existing term or new term to post you need to use wp_set_post_terms by checking with term_exists and using wp_insert_term if it doesn't.

Something like this:

$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_author'       =>  $author_id,
        'post_name'         =>  $slug,
        'post_title'        =>  $title,
        'post_content'      =>  $content,
        'post_status'       =>  'publish',
        'post_type'         =>  'post'
    )
);
$taxonomy = '<CUSTOM_TAXONOMY_SLUG>';
if (term_exists('samsung', $taxonomy)) {
    $terms = array('samsung');
    wp_set_post_terms( $post_id, $terms, $taxonomy, true);
} else {
    $term = 'samsung';
    $inserted_term = wp_insert_term( $term, $taxonomy);
    if(!is_wp_error($inserted_term)) {
        wp_set_post_terms( $post_id, $term, $taxonomy, true);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.