0

when the category comes from a form, how I can use in wp_insert_post?

$my_post = array(); 
$my_post['post_author'] = $userid; 
$my_post['post_title'] = $name; 
$my_post['post_name'] = str_replace(' ', '-', $name); 
$my_post['post_category'] = $selected = $_POST['postcats']; 
$newpost_id= wp_insert_post( $my_post );

is it correct? what is it wrong? thanks a lot

1 Answer 1

0

You need to create the category first, then add it to the post:

$my_post = array(); 
$my_post['post_author'] = $userid; 
$my_post['post_title'] = $name; 
$my_post['post_name'] = str_replace(' ', '-', $name);
$cat_id = wp_create_category($_POST['postcats'], 0); // we create the category and we get the ID, the 0 is for no parent category
$my_post['post_category'] = array($cat_id);//this value is an array not a single value 
$newpost_id= wp_insert_post( $my_post );

you can also just create the post and add the category later with wp_set_post_categories

8
  • It doens't work This is the rror: Fatal error: Call to undefined function wp_create_category() in ... inc/custom-abc.php on line 31 Commented Feb 11, 2017 at 19:03
  • The line is this: $cat_id = wp_create_category($_POST['postcats']); // we create the category and we get the ID, the 0 is for no parent category I gave the list of category (this is a custom type) Commented Feb 11, 2017 at 19:08
  • this is my function: Commented Feb 11, 2017 at 19:32
  • function create_post_from_user($email, $name, $address, $city, $country, $phone, $subcategory, $userid, $mobile) { global $post,$wpdb,$tag; $directory_url_1=get_option('_iv_directory_url_1'); if($directory_url_1==""){$directory_url_1='azienda';} $directory_url_2=get_option('_iv_directory_url_2'); if($directory_url_2==""){$directory_url_2='professionisti';} Commented Feb 11, 2017 at 19:33
  • $query = "SELECT tt.term_id, taxonomy, parent FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE t.slug='" . $subcategory . "' AND taxonomy in ('" .$directory_url_2.'-category' ."','".$directory_url_1.'-category'."')"; $taxonomy_term = $wpdb->get_results($query, OBJECT); $parentCategoryId=$taxonomy_term[0]->parent; $my_post = array(); $my_post['post_author'] = $userid; $my_post['post_title'] = $name; $my_post['post_name'] = str_replace(' ', '-', $name); $newpost_id= wp_insert_post( $my_post ); Commented Feb 11, 2017 at 19:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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