Just in case this helps anyone else out…
Creating an entire plugin seemed like a lot of work to perform a relatively simple task, so I decided to comb through the plugin’s files and see what was actually happening. Lo and behold, all you need is a couple of quick PHP scripts and a JS file to manage the AJAX request.
PHP for your functions.php file:
function ws_enqueue_acf_scripts() {
$admin_js_path = get_template_directory_uri() . '/path/to/js/ws-acf-conditional-taxonomy.js';
wp_enqueue_script( 'conditional-taxonomy-rule-acf', $admin_js_path, array( 'jquery','acf-input' ));
}
//enqueue script after ACF is initialized/loaded
add_action( 'acf/init', 'ws_enqueue_acf_scripts' );
//PHP function called by JS file to get taxonomy terms based on the current selection
function fetch_taxonomy_terms(){
if ( is_admin() && ! wp_doing_ajax() ) {
exit("No naughty business please");
}
$taxonomy = sanitize_text_field($_REQUEST['taxonomy']);
$terms = get_terms(
$taxonomy,
array(
'hide_empty' => false,
'fields' =>'id=>name'
)
);
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
echo json_encode($terms);die;
}
}
add_action( 'wp_ajax_load_taxonomy_term_choices', 'fetch_taxonomy_terms' );
& here’s the chunk of jQuery from the JS file:
(function($){
var parseString = function( val ){
return val ? '' + val : '';
};
var isEqualTo = function( v1, v2 ){
return ( parseString(v1).toLowerCase() === parseString(v2).toLowerCase() );
};
var inArray = function( v1, array ){
// cast all values as string
array = array.map(function(v2){
return parseString(v2);
});
return (array.indexOf( v1 ) > -1);
}
// Add New option in dropdown options to compare when taxonomy is slected in conditional rule
var TaxonomyEqualTo = acf.Condition.extend({
type: 'taxonomyEqualTo',
operator: '==',
label: ('Taxonomy is equal to'),
fieldTypes: [ 'taxonomy' ],
match: function( rule, field ){
var val = field.val();
if( val instanceof Array ) {
return inArray( rule.value, val );
} else {
return isEqualTo( rule.value, val );
}
},
choices: function( fieldObject ){
var choicesaa = [];
jQuery.ajax({
type : "post",
dataType : "json",
url : acf.get('ajaxurl'),
async: false,
data : {action:'load_taxonomy_term_choices',taxonomy:fieldObject.$setting('taxonomy select').val()},
success: function(response) {
$.each(response, function(i, item) {
choicesaa.push({
id: i,
text: (item)
});
})
}
});
return choicesaa;
},
});
acf.registerConditionType( TaxonomyEqualTo );
var TaxonomyNotEqualTo = TaxonomyEqualTo.extend({
type: 'taxonomyNotEqualTo',
operator: '!=',
label: ('Taxonomy is not equal to'),
match: function( rule, field ){
return !TaxonomyEqualTo.prototype.match.apply(this, arguments);
}
});
acf.registerConditionType(TaxonomyNotEqualTo);
})(jQuery);
I’m not going to explain what all of that does, but I can tell you it worked like a charm.
Here’s a quick bit of SASS code to make it behave horizontally:
.acf-taxonomy-field{
ul.acf-checkbox-list{
&.acf-bl {
> li {
float: left;
margin-right: 20px;
}
}
}
}
Although I don’t think that the original issue is still relevant (the select2 search field searches through sub-terms just fine as far as I can tell), here is a method to remove the hyphen from a specific taxonomy field. This is useful in my case where I am creating a select list with child terms only, and it’s cleaner to have them listed without the hyphen:
add_filter( 'acf/fields/taxonomy/result', 'xyz_remove_hyphen_from_tax_terms', 10, 4);
function xyz_remove_hyphen_from_tax_terms ($title, $term, $field, $post_id){
if ($field['key'] == 'field_123'){ // Your custom field key
$title = str_replace('- ', '', $title);
}
return $title;
}
I figured out how to do this but do not recommend it. A better way would be to add an “other” option which reveals a text field and then use the acf/save_post
action to add the content of the text field as a new taxonomy term.
Here is the process to solve the originally asked problem. Start by creating a user named “Website Visitor” or similar with Subscriber-level access. Then integrate the following code.
// Allow all users, even non-signed in users to manage categories/taxonomies
add_filter( 'user_has_cap', 'custom_allow_all_edit_tax');
function custom_allow_all_edit_tax($allcaps){
$allcaps['manage_categories'] = true;
return $allcaps;
}
// Set the user to your manually created "Website Visitor" user with Subscriber-level access
add_action('after_setup_theme', 'custom_set_user_website_visitor');
function custom_set_user_website_visitor(){
// You will want to check if the user is not logged in already before modifying the user here
wp_set_current_user(#); // Your Website Visitor's user number
}
I’m trying to do the same thing, but have a different problem I’d like to solve before digging into the capabilities. When I click the “add new taxonomy” plus button I get a popup with a form to add a new one, but when I submit that form, it also submits the main “new post” form on the page. Any ideas?
The only reason get_the_terms should be returning more than one is if more than one is selected for that post. From the doc.
get_the_terms( int|WP_Post $post, string $taxonomy )
should only get the terms selected for the post in the specified taxonomy
This is the solution I ended up using. For whatever reason, my rewrites weren’t working when I was registering the CPT and taxonomy via ACF (order didn’t matter); with registering them as code in functions.php, then it worked.
Sure, here’s a direct idea that you can use to display the taxonomy hierarchy on your WordPress website:
You can use the get_ancestors() function in WordPress to retrieve the ancestors of a taxonomy term. This function returns an array of term IDs, which you can then use to display the hierarchy.
Here’s an example code snippet that you can use:
<?php
// Get the current taxonomy term
$term = get_queried_object();
// Get the ancestors of the current term
$ancestors = get_ancestors( $term->term_id, $term->taxonomy );
// If there are ancestors, display them
if ( $ancestors ) {
// Reverse the order of ancestors to display them from parent to child
$ancestors = array_reverse( $ancestors );
// Loop through the ancestors and display them
for each ( $ancestors as $ancestor ) {
$ancestor_term = get_term( $ancestor, $term->taxonomy );
echo esc_html( $ancestor_term->name ) . ‘ – ‘;
}
}
// Display the current term
echo esc_html( $term->name );
?>
This code will retrieve the ancestors of the current taxonomy term and display them with the current term, separated by a dash. You can modify the output as per your requirements.
OK, got that cleared away. However, when I assign someone some roles, then update, I can then go into each taxonomy for those roles and the person is *not* in them! That’s the part that’s killing me right now…
Having taxonomy show up in right hand column when editing/adding a post is done by selecting it from screen options.
Provided of course that the taxonomy in question is associated with the post_type.
This can be done in functions.php
register_taxonomy(“imaTaxonomy”, [“imaPostType”]);
Thanks for the reply @curtisfraser ! I’m guessing there is no official ACF support here 🙁
ok, so here is where I was making my mistake. I have one taxonomy for each role. I was trying to put one of those in the Taxonomy field. Instead I created a new Taxonomy named ‘Role’ and when I use *that* one, I get the option to pick one of three roles.
Now I can’t figure out how to get taxonomies to show up in various places. I pretty much have all settings matched/duplicated, but some show up under CPT, some show in the right-hand column in CPT, and some just don’t show up at all 🙁
super easy to do even with free version.
1. Create field group for the post_type (Post Type is equal to Cast and Crew)
2. create a field of type Taxonomy, select what taxonomy to use, appearance of ‘Select’
3. The new select field will now appear when editing/creating a “Cast and Crew” post
Do ACF people answer these questions? Or do they hope we just help each other. I’ve seen many questions with no responses.
Short answer is no.
WP requires some permission set capabilities of the taxonomy to add terms. Since the user is not logged in they have no permissions. I’m not 100% sure what capability this is tied to, I think it is ‘manage_terms’ and by default this is tied to the ‘manage_categories’ permission.
It may be possible to use the user_has_cap filter to allow a logged out user to have this permission, but I can find no specific information on this. I would start digging deeper here.
And here is what I did in Elementor:
(attached file01)
So it definitely loads something correct, which is the ID of the taxonomy:
(attached file02)
In this case 59
But even if I switch the value as showed in my original post this is still the ID and not the value/term that is showing up.
Un grand salut aussi 🙂
I’ll try to change the content of my post so i can actually post it
Au cas où d’autres personnes rencontrent le meme problème on continue en Anglais ? 🙂
I am definitely not a coder/dev and since the latest release of ACF what I am trying, or anyway, achieved so far, has been done without a single bit of code.
My bad, I forgot to specify that I am also using Elementor.
But here is what I have done:
I have created a new taxonomy:
Salut aussi !
Au cas où d’autres personnes rencontrent le meme problème on continue en Anglais ? 🙂
I am definitely not a coder/dev and since the latest release of ACF what I am trying, or anyway, achieved so far, has been done without a single bit of code.
My bad, I forgot to specify that I am also using Elementor.
But here is what I have done:
I have created a new taxonomy:
https://prnt.sc/SblxWOHBmACi
https://prnt.sc/QpWKI3Qa41-S
https://prnt.sc/A8kIAtrZXW6m
Salut aussi !
Au cas où d’autres personnes rencontrent le meme problème on continue en Anglais ? 🙂
I am definitely not a coder/dev and since the latest release of ACF what I am trying, or anyway, achieved so far, has been done without a single bit of code.
My bad, I forgot to specify that I am also using Elementor.
But here is what I have done:
I have created a new taxonomy:
https://prnt.sc/SblxWOHBmACi
https://prnt.sc/QpWKI3Qa41-S
https://prnt.sc/A8kIAtrZXW6m
Thanks, @hube2 for the answer! It helped me too.
I did find a way to simplify the conditional logic to one condition by selecting “Value is equal to” and entering the taxonomy ID.
Please note that if you have more than one term, you will need to select “Value Contains” instead to make it work.
Applying this to the earlier example, if you want both the FREE and PAID terms to trigger different actions, you have to use “Value Contains”.
Thanks a lot John, for your reply !!!
I wasn’t aware that the acf/fields/taxonomy/query filter works with ajax based request.
It’s perfect to solve my issue.
Have a good day !
Since you are using the acf/fields/taxonomy/wp_list_categories hook you can limit the terms available in the “parent” field by using the acf/fields/taxonomy/query filter.
For anyone that is reading this that is using a select field rather than a checkbox or radio field like the OP and using acf/fields/taxonomy/query to limit selections you can do this by using different filters for each. A simple example
funcition my_taxonomy_filter($args, $field, $post_id) {
// this is the filter for limiting selection is the taxonomy field
}
add_filter('acf/fields/taxonomy/query/field_key=field_XXXXXXX', 'my_taxonomy_filter', 10, 3);
function my_secondary_taxonomy_filter($args, $field, $post_id) {
// this is the secondary filter used when getting values to show in parents
}
// this action is fired when then add term popup is loaded
// what we want to do here is switch the filter to use when adding a term
// done with a low priority to switch it before ACF does the query
add_action('wp_ajax_acf/fields/taxonomy/add_term', 0);
function switch_taxonomy_filters() {
// switch which filter to use when adding terms
remove_filter('acf/fields/taxonomy/query/field_key=field_XXXXXXX', 'my_taxonomy_filter', 10);
add_filter('acf/fields/taxonomy/query/field_key=field_XXXXXXX', 'my_secondary_taxonomy_filter', 10, 3);
}
You should also not that if you are using the acf/fields/taxonomy/query for your field and you don’t want the parent field filtered that you should still remove the main filter because as you can see, it operates on both the field and the parent and your parents will only show what is available in the main field.
Go to your taxonomy/term list in the admin. Hover over the link to the term, the URL contains the term ID
It’s really new, so I don’t really have an answer. If there are any filters that can be used in ACF they are not documented, but I can’t really find anything useful in the ACF code.
You can probably use the WP hook register_taxonomy_args.
For an ACF specific filter you’d probably need to contact the developers.
You can create conditional logic based on a taxonomy field, but it is not straight forward. For this you need to know the ID of the term you want the field to appear on. Lets assume that the term ID of “Paid” is 1. In this case your conditional logic rules would be.
Show this field if
Taxonomy Field | Selection is greater than | 0 AND
Taxonomy Field | Selection is less than | 2
Ohhhhh, you’re wanting it in conditional logic, not as a location rule on an overall field group. You can definitely assign field groups based on if an item is given a certain taxonomy term so you could say display this set of fields if the taxonomy term for admissions is equal to free or equal to paid. It’s just something that has to be done in separate sets of fields.
You should see taxonomy terms able to be selected like this if you choose Post Taxonomy as the first rule dropdown.
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.