acf_field_taxonomy::ajax_add_term() public ACF 5.2.3
description
{} Это метод класса: acf_field_taxonomy{}
Хуков нет.
Возвращает
$post_id. (int)
Использование
$acf_field_taxonomy = new acf_field_taxonomy();
$acf_field_taxonomy->ajax_add_term();
Список изменений
Код acf_field_taxonomy::ajax_add_term() acf field taxonomy::ajax add term
ACF 5.9.1
<?php
function ajax_add_term() {
// vars
$args = wp_parse_args($_POST, array(
'nonce' => '',
'field_key' => '',
'term_name' => '',
'term_parent' => ''
));
// verify nonce
if( !acf_verify_ajax() ) {
die();
}
// load field
$field = acf_get_field( $args['field_key'] );
if( !$field ) {
die();
}
// vars
$taxonomy_obj = get_taxonomy($field['taxonomy']);
$taxonomy_label = $taxonomy_obj->labels->singular_name;
// validate cap
// note: this situation should never occur due to condition of the add new button
if( !current_user_can( $taxonomy_obj->cap->manage_terms) ) {
wp_send_json_error(array(
'error' => sprintf( __('User unable to add new %s', 'acf'), $taxonomy_label )
));
}
// save?
if( $args['term_name'] ) {
// exists
if( term_exists($args['term_name'], $field['taxonomy'], $args['term_parent']) ) {
wp_send_json_error(array(
'error' => sprintf( __('%s already exists', 'acf'), $taxonomy_label )
));
}
// vars
$extra = array();
if( $args['term_parent'] ) {
$extra['parent'] = (int) $args['term_parent'];
}
// insert
$data = wp_insert_term( $args['term_name'], $field['taxonomy'], $extra );
// error
if( is_wp_error($data) ) {
wp_send_json_error(array(
'error' => $data->get_error_message()
));
}
// load term
$term = get_term($data['term_id']);
// prepend ancenstors count to term name
$prefix = '';
$ancestors = get_ancestors( $term->term_id, $term->taxonomy );
if( !empty($ancestors) ) {
$prefix = str_repeat('- ', count($ancestors));
}
// success
wp_send_json_success(array(
'message' => sprintf( __('%s added', 'acf'), $taxonomy_label ),
'term_id' => $term->term_id,
'term_name' => $term->name,
'term_label' => $prefix . $term->name,
'term_parent' => $term->parent
));
}
?><form method="post"><?php
acf_render_field_wrap(array(
'label' => __('Name', 'acf'),
'name' => 'term_name',
'type' => 'text'
));
if( is_taxonomy_hierarchical( $field['taxonomy'] ) ) {
$choices = array();
$response = $this->get_ajax_query($args);
if( $response ) {
foreach( $response['results'] as $v ) {
$choices[ $v['id'] ] = $v['text'];
}
}
acf_render_field_wrap(array(
'label' => __('Parent', 'acf'),
'name' => 'term_parent',
'type' => 'select',
'allow_null' => 1,
'ui' => 0,
'choices' => $choices
));
}
?><p class="acf-submit">
<button class="acf-submit-button button button-primary" type="submit"><?php _e("Add", 'acf'); ?></button>
</p>
</form><?php
// die
die;
}