Home › Forums › Backend Issues (wp-admin) › Default value for the taxonomy field type: Solution
Based on actual changes with custom post types there exist based on this post: https://support.advancedcustomfields.com/forums/topic/default-value-for-the-taxonomy-field-type/
a new solution:
public function pf_exhibition_index_load( $field ) {
$tax = get_taxonomy( 'pf_exhibition_template' );
$slug = $tax->default_term['slug'];
if ( $term = get_term_by( 'slug', $slug, 'pf_exhibition_template' ) ) {
$field['default_value'] = $term->term_id;
}
return $field;
}
Registering a custom taxonomy allowes to define a default term – with this solution and the option to translate your term a default term in ACF is possible.
$args = array(
'labels' => $labels,
'default_term' => array(
'name' => _x( 'Default', 'Default template taxonomy name', 'picture-frame' ),
'slug' => _x( 'default', 'Default template taxonomy slug', 'picture-frame' ),
'description' => __( 'This is the default template.', 'picture-frame' ),
),
Now the select2 field which is ACF-AJAX powered couldnt use our “default_value”. Therefore i tried a new approach by using a second AJAX function:
The JS-Part:
acf.addAction('show_field/key=field_pf_exhibition_template', function() {
var pf_template = acf.getField('field_pf_exhibition_template');
data = pf_acf_fetch_data('pf_get_exhibition_template_standard', id);
$.when(data).then(function(data){
pf_template.select2.addOption({
id: data.id,
text: data.name,
selected: true
});
});
});
and the corresponding PHP part:
add_action( 'wp_ajax_pf_get_exhibition_template_standard', array( $this, 'pf_ajax_get_exhibition_template_standard' ) );
public function pf_ajax_get_exhibition_template_standard() {
if ( !wp_verify_nonce( $_POST['nonce'], 'acf_nonce' ) ) {
die();
}
$tax = get_taxonomy( 'pf_exhibition_template' );
$slug = $tax->default_term['slug'];
$term = get_term_by( 'slug', $slug, 'pf_exhibition_template');
if ( $term = get_term_by( 'slug', $slug, 'pf_exhibition_template' ) ) {
$data = array( 'id' => $term->term_id, 'name' => $term->name );
}
else {
$data = false;
}
echo json_encode($data);
exit;
}
Now it works like a charm.
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.