Home > Net >  wp_insert_post custom taxonomy multiple Category not added
wp_insert_post custom taxonomy multiple Category not added

Time:03-02

I have a custom post type jobs and a custom taxonomy jobCategory. wp_insert_post() and it works. When a user selects multiple jobCategory, only one selected category is recorded in the database. please guide me.

if (isset($_POST['send'])) {
$post_id = wp_insert_post(array(
    'post_type' => 'jobs',
    'post_author' => get_current_user_id(),
    'post_title' => $_POST['title'],
    'post_content' => $_POST['description'],
    'post_status' => 'draft',
));
wp_set_object_terms($post_id, intval($_POST['category']), 'jobCategory');
add_post_meta($post_id, 'price', $_POST['price']);
add_post_meta($post_id, 'time', $_POST['time']);
if (isset($_FILES['file'])) {
    require_once(ABSPATH . 'wp-admin/includes/file.php');
    $uploadedfile = $_FILES['file'];
    $upload_overrides = array(
        'test_form' => false
    );
    $movefile = wp_handle_upload($uploadedfile, $upload_overrides);
    add_post_meta($post_id, 'file', $movefile['url']);
    add_post_meta($post_id, 'payToSee', 0);}
wp_redirect('my-ads');

}

<div id="wpap-content"> <div > <div > <div > <form action="" method="POST" enctype="multipart/form-data"> <div > <label for="title"> Title </label> <input required type="text" id="title" name="title" > </div><div > <label for="description"> details </label> <textarea name="description" id="description"  cols="30" rows="10"></textarea> </div><div > <label for="category"> category </label> <select id="js-choice" id="category" name="category[]" multiple="multiple"> <?php $terms=get_terms([ 'taxonomy'=> 'jobCategory', 'hide_empty'=> false,]); foreach ($terms as $cat){?> <option value="<?=$cat->term_id ?>"><?=$cat->name ?></option> <?php}?> </select> </div><div > <label for="price"> Price </label> <input required type="text" id="price" name="price" > </div><div > <label for="time"> Time </label> <input required type="text" id="time" name="time" > </div><div > <label for="file"> Files </label> <input type="file" id="file" name="file" > </div><button value="1" name="send" type="submit" >Submit </button> </form> </div></div>

CodePudding user response:

The problematic line is:

wp_set_object_terms($post_id, intval($_POST['category']), 'jobCategory');

You do intval to array and you get the first value.

You can convert the values with array_map.

$categories = array_map('intval', $_POST['category']);
wp_set_object_terms($post_id, $categories, 'jobCategory');

I also suggest not getting data without filtering from the user. You need to use filters.

  • Related