我使用的方法來自此tutorial,它適用於在前端創建自定義帖子(sugestie)。前端REST API插入自定義帖子類型並分配自定義分類
問題是,我無法找到一種方法,當表單被提交時,分配一個自定義分類到這些職位。在後端它運作良好。
這是分類
register_taxonomy(
'cat_sugestie', //The name of the taxonomy.
'sugestie', //post type name
array(
'labels' => array(
'name' => _x('Categorii', 'taxonomy general name', 'books'),
'singular_name' => _x('Categorie', 'taxonomy singular name', 'books'),
'search_items' => __('Cauta Categorii', 'books'),
'all_items' => __('Toate Categoriile', 'books'),
'parent_item' => __('Categorie parinte', 'books'),
'parent_item_colon' => __('Categorie parinte:', 'books'),
'edit_item' => __('Editeaza Categorie', 'books'),
'update_item' => __('Update Categorie', 'books'),
'add_new_item' => __('Adauga Categorie', 'books'),
'new_item_name' => __('Numele noii Categorii', 'books'),
'menu_name' => __('Categorii', 'books'),
), //Display name
'hierarchical' => true,
'query_var' => true,
'show_ui' => true,
'show_in_rest' => true,
'rest_base' => 'cat_sugestie',
'show_admin_column' => true,
'rewrite' => array(
'slug' => 'cat_sugestie', // base slug that will display before each term
'with_front' => false // display the category base before
),
'capabilities' => array(
'assign_terms' => 'read',
)
)
);
這是我得到的分類形式
<div>
<label for="post-submission-cat">
<?php _e('Chose a category', 'your-text-domain'); ?>
</label>
<select name="post-submission-cat" id="post-submission-cat">
<?php if ($cats = get_terms(array('taxonomy' => 'cat_sugestie', 'hide_empty' => false))) {
foreach ($cats as $cat) { ?>
<option value="<?php echo $cat->term_id; ?>"><?php echo $cat->name; ?></option>
<?php
}
} ?>
</select>
</div>
這是提交後
jQuery(document).ready(function ($) {
$('#post-submission-form').on('submit', function(e) {
e.preventDefault();
var title = $('#post-submission-title').val();
var content = $('#post-submission-content').val();
var cat = parseInt($('#post-submission-cat').val());
var data = {
title: title,
content: content,
post_type: 'sugestie',
status: 'pending',
//cat_sugestie: cat - this doesn't work
};
$.ajax({
method: "POST",
url: POST_SUBMITTER.root + 'wp/v2/sugestie',
data: data,
beforeSend: function(xhr) {
xhr.setRequestHeader('X-WP-Nonce', POST_SUBMITTER.nonce);
},
success : function(response) {
alert(POST_SUBMITTER.success);
},
fail : function(response) {
alert(POST_SUBMITTER.failure);
}
});
});
});
因此,它是JS代碼可能做到這一點? 謝謝!
你有答案嗎? – input