John Davidson

php - Insert number value to terms with ACF

0 comments
Message:


I have issue with inserting terms while typing select input field. Strings will be correctly inserted but if there is date or number values for terms then it inserts term ID.


I have a lot term fields and some of them are numeric fields like date, mileage, etc..


My Code:


function jl_insert_term_if_not_exists($term, $taxonomy) {
if (empty($term) || is_numeric($term)) { //tried is_string() then every value inserted as term ID
return $term;
}

if ($result = term_exists($term, $taxonomy)) {
return $result['term_id'];
}

$result = wp_insert_term($term, $taxonomy);

if (!is_wp_error($result)) {
return $result['term_id'];
}
}

function jl_acf_update_value( $value, $post_id, $field ) {
if ($field['type'] == 'taxonomy'
&& in_array($field['field_type'], array('select', 'multi_select'))
&& strpos($field['wrapper']['class'], 'acf-select-tags') !== false)
{
if (!is_array($value)) {
if ($term_id = jl_insert_term_if_not_exists($value, $field['taxonomy'])) {
$value = $term_id;
}
} else {
foreach ($value as &$item_value) {
if ($term_id = jl_insert_term_if_not_exists($item_value, $field['taxonomy'])) {
$item_value = $term_id;
}
}
}
}

return $value;
}
add_filter('acf/update_value', 'jl_acf_update_value', 5, 3);
function jl_acf_input_admin_footer() {
?>
<script type="text/javascript">
(function($) {
acf.add_filter('select2_args', function( args, $select, settings, $field, instance ){
if ($field.hasClass('acf-select-tags')) {
console.log($field.hasClass('acf-select-tags'));
args.tags = true
}

return args;
});
})(jQuery);
</script>
<?php
}
add_action('acf/input/admin_footer', 'jl_acf_input_admin_footer');


My Answer:
&& $field['taxonomy'] == 'category') { $value = jl_insert_term_if_not_exists($value, $field['taxonomy']); } return $value;}__add_filter('acf/update_value', 'jl_acf_update_value', 10, 3);?>

In the code above, the `jl_insert_term_if_not_exists` function checks if the term is empty or numeric. If it is, it returns the term as is. If the term already exists, it returns the term ID. If the term does not exist, it inserts the term and returns the term ID.

The `jl_acf_update_value` function is used as a filter for the ACF `update_value` action. It checks if the field type is taxonomy and the taxonomy is category, and then calls the `jl_insert_term_if_not_exists` function to insert or retrieve the term ID.

Make sure to adjust the taxonomy check in the `jl_acf_update_value` function if you have multiple taxonomies that need to handle numeric values differently.

Rate this post

4 of 5 based on 6150 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us