theKing
theKing

Reputation: 844

Wordpress wp_insert_post is creating new Taxonomy term when creating new custom post

In my WordPress v5.5.1, I am using public front-end form to create custom post type. I am saving the form data as custom post with below code:

function save_function() {
   // MESSAGE FIELDS
    $public_post = array(
        'post_title' => filter_input(INPUT_POST, 'title'),
        'post_author' => 1,
        'post_type' => 'message',
        'post_status' => 'pending',
        'tax_input' => array(
            'my_custom_taxonomy' => array(filter_input(INPUT_POST, 'subject')) // subject is a HTML select which captures option value contains term_id which is generated using get_terms.
        )
    );

    wp_insert_post($public_post);
}

Instead of 'tax_input' tag this post to the existing custom_taxonomy term, it is creating a duplicate term with term_id as term name.

Upvotes: 0

Views: 891

Answers (1)

Sayed Mohamed
Sayed Mohamed

Reputation: 183

Hello Plese Try This Func

   function save_function()
{

    $subject_term = 'subject';
    $my_subject_term = term_exists($subject_term, 'my_custom_taxonomy');   // check if term in website or no
    // Create Term if it doesn't exist
    if (!$my_subject_term) {
        $my_subject_term = wp_insert_term($subject_term, 'my_custom_taxonomy');
    }
    $custom_tax = array(
        'my_custom_taxonomy' => array(
            $my_subject_term['term_taxonomy_id'],
        )
    );

    // MESSAGE FIELDS
    $public_post = array(
        'post_title' => filter_input(INPUT_POST, 'title'),
        'post_author' => 1,
        'post_type' => 'message',
        'post_status' => 'pending',
        'tax_input' => $custom_tax
    );

    $post_id = wp_insert_post($public_post);

    
}

Upvotes: 0

Related Questions