Assigning categories to custom post types via a front-end form; only works for native post type

Question

I have a front-end form, for creating a new post. I can create a new custom post with it. But can’t assign a category for it. I can assign a category only if I change the post type to regular post. So, The code below creates a new custom post but no category is assigned. I tried whatever way I knew and no result.

I used wp_insert_post function and tax_input as its parameter (Link).

Custom post type and its related taxonomy name (Both created using CPT UI plugin.): companies | company_type

My php code:

if(isset($_POST['title'])){
    
    $categories2 = array(61); // 61 is the key of an existing category in company_type

    $my_post = array(

    'post_title' => $_POST['title'],
    'post_content' => $_POST['description'],
    'post_status' => 'publish', 
    'post_type' => 'companies', //My custom post type. Is created with CPT UI plugin.
    'tax_input'    => array(
                     'company_type' => $categories2 //company_type is the Taxomony Name
                )
);
    
    $post_id = wp_insert_post($my_post);
 
    echo 'New Post Saved !';
    
    die;
}

I used post_category instead of tax_input thing and still it didn’t work:

'post_category' => $categories2,  // I read that "[this is] Usable for custom
 //taxonomies too", But it only worked for regular posts for me.

I tried to use functions like wp_set_post_terms and wp_set_object_terms but no result. Like this:

wp_set_post_terms( $post_id, $categories2, 'company_type', false ); // I used this within
//the same code I inserted above, after the line of "wp_insert_post".

Also I read that assigning taxonomies may needs to have proper user privileges. I am an admin user, So it shouldn’t be the problem.

I want to know what’s my mistake. And please explain about your code and where should I insert it.

0
Davood Kazemi 2 months 0 Answers 11 views 0

Leave an answer