wp_insert_post 未添加自定义分类法多个类别

wp_insert_post custom taxonomy multiple Category not added

我有一个自定义 post 类型 jobs 和一个自定义分类法 jobCategory。 wp_insert_post() 并且有效。 当用户选择多个jobCategory时,数据库中只会记录一个选择的类别。 请指导我。

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 class="col-12"> <div class="card"> <div class="card-body"> <form action="" method="POST" enctype="multipart/form-data"> <div class="form-group"> <label for="title"> Title </label> <input required type="text" id="title" name="title" class="form-control"> </div><div class="form-group"> <label for="description"> details </label> <textarea name="description" id="description" class="form-control" cols="30" rows="10"></textarea> </div><div class="form-group"> <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 class="form-group"> <label for="price"> Price </label> <input required type="text" id="price" name="price" class="form-control"> </div><div class="form-group"> <label for="time"> Time </label> <input required type="text" id="time" name="time" class="form-control"> </div><div class="form-group"> <label for="file"> Files </label> <input type="file" id="file" name="file" class="form-control"> </div><button value="1" name="send" type="submit" class="btn text-center btn-primary">Submit </button> </form> </div></div>

有问题的行是:

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

您对数组执行 intval 并获得第一个值。

您可以使用 array_map 转换值。

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

我还建议不要在未过滤用户的情况下获取数据。您需要使用 filters.