Support

Account

Home Forums Feature Requests Conditional Logic using Taxonomy field

Solving

Conditional Logic using Taxonomy field

    • buylov

    • June 7, 2016 at 5:30 pm

    Please add this feature! I also really need it!

  • It is definitely a MUST HAVE! 🙁

  • Like to have this feature too… Infact i need it for my site.

  • For those who aren’t afraid to write a little bit of JS to self-solve their problem. I put together a blog post explaining this – http://idealienstudios.com/crazy-with-conditionals/ – and specific JS Gist for reference.

    Enjoy!

  • +1 vote 🙂

  • Ok Guys, my solution:

    	function my_acf_admin_head() {
    		global $post_type;
    		if( 'midias_type' == $post_type ) : ?>
    		<script type="text/javascript">
    			(function($){
    
    				acf.add_action('ready', function( $el ){
    
    					var container = $('.acf-field');
    					var $field = $('.acf-checkbox-list input');
    
    					container.each(function ( index) {
    						if(!$(this).hasClass('acf-field-taxonomy')) {
    							$(this).addClass("hidden-by-conditional-logic");
    						}
    					});
    
    					$field.on('click', function (evt) {
    						var ele = $(this).val();
    						container.removeClass('hidden-by-conditional-logic');
    						if(ele == '53') {
    							$('[data-name="arquivo"]')
    									.siblings(':not(.acf-field-taxonomy,[data-name="capa"])')
    									.addClass('hidden-by-conditional-logic');
    						} else if(ele == 52) {
    							$('[data-name="fotos"]')
    									.siblings(':not(.acf-field-taxonomy)')
    									.addClass('hidden-by-conditional-logic');
    						} else if(ele == 51) {
    							$('[data-name="video"]')
    									.siblings(':not(.acf-field-taxonomy,.acf-field-text)')
    									.addClass('hidden-by-conditional-logic');
    						}
    					});
    
    					$('input[type="radio"]:checked' ).click();
    				});
    
    			})(jQuery);
    		</script>
    		<?php endif;
    	}
    
    	add_action('acf/input/admin_head', 'my_acf_admin_head');
  • I thank Idealien, your solution served as the basis of my code.

  • This is indeed something and I congratulate you for that, now the next step is doing this but dynamicaly and integrated with ACF.

    Come on ACF team, you have already a good part done, now it’s up to you to integrate it! 🙂

    Or, someone can do a plugin for that… just an idea! 😉

  • Until ACF builds this in you will need to build conditional logic for specific fields the way that @marlonleite has given in the example.

    I’ve been looking at the ACF JS code for conditional logic and here’s the problem with using fields other that choice fields. ACF does not make any AJAX requests here. It simply looks at the fields in the editor. In order to use any other type of field, like taxonomy, relationship, post object or user, ACF would need to make an AJAX request to get the values that it would need to display. I’m guessing that this would be a major change.

    As far as builing an add on there isn’t any way to extend the JS code that’s already there. Someone would need to override what is there and replace it with new code. I don’t know if this is possible. If there is anyone here that knows a great deal about JS and jQuery and you can explain how to override existing functions, maybe it would be possible for someone to write an extension for an add on. If your interested the code for conditional logic is located on about line 1500 of /advanced-custom-fields-pro/assets/js/acf-field-group.js

    If someone can tell me how to go about overriding those function I might be willing to give it a shot if I can find the time.

    I know that this is a long standing request, but Elliot is the only developer, there really isn’t a “Team”. I’m sure that this is on the to do list, it probably just has a lower priority than some of the more important changes that need to be made, like the proper use of term meta which he’s started working on.

    • Beee

    • October 8, 2016 at 8:25 am

    Like many I also wanted to have conditional fields related to a taxonomy and I solved this issue with only 14 lines of code (not counting commented lines)… I think several people may benefit from this.

    I first had a simple radio button as for a custom field called sex.
    Based upon this selection some other fields came into action, such as cup size for women.

    I then decided to make a taxonomy for sex. I didn’t add an ACF field for it. Instead I added an acf/save_post action, which changes the taxonomy on post save, based on the value which was entered in the ACF field.

    So the page loads the custom field value and on save it changes the taxonomy if those values are not the same.

    Add this to functions.php

    
    function change_post_taxonomy_44582( $post_id ) {
        // bail if no ACF data
        if ( empty($_POST['acf']) ) {
            return;
        }
        // get term id from $post_id (only 1 value is allowed, so it returns 1 value only)
        $stored_sex = wp_get_post_terms($post_id, 'sd_sex');
        // get submitted value from acf form
        $posted_sex = $_POST['acf']['field_57e3ed6c92fd1'];
        // get term_id for the submitted value
        $term_id    = get_term_by( 'name', $posted_sex, 'sd_sex' );
        // if stored value is not equal to posted value, then update terms
        if ( $stored_sex != $posted_sex ) {
            wp_set_object_terms( $post_id, $term_id->term_id, 'sd_sex' );
        }
    }
    add_action('acf/save_post', 'change_post_taxonomy_44582', 20);
    
    

    Hope this helps some people.

  • Good catch! Thanks!

  • +1 and thanks

  • Kind of annoying that this still has not been implemented after almost 3.5 years, but for what it’s worth: +1

    Meanwhile I modified Beee’s solution to accept more than one value as I needed it to work with checkboxes.

    I’m sure someone more experienced can improve on this, but here it is for now:

    
    function change_post_taxonomy( $post_id ) {
        // bail if no ACF data
        if ( empty($_POST['acf']) ) {
            return;
        }
        
        // Limit to certain post types if needed
        if(get_post_type($post_id) == 'whatever') {
    	    
    	    $term_ids = array();
    		
    	    // get term id from $post_id
    	    $stored_role = wp_get_post_terms($post_id, 'category');
    	    
    	    // get submitted value from acf form by field key
    	    $posted_roles = $_POST['acf']['field_582c317422b74'];
    	    
    	    // get term_id for the submitted value(s)	    
    	    foreach ($posted_roles as $posted_role) { 
    			
    			$term = get_term_by( 'name', $posted_role, 'category' );
    			$term_id = $term->term_id;
    			$term_ids[] = $term_id;
    		
    		}
    	    
    	    // if stored value(s) is/are not equal to posted value(s), then update terms
    	    if ( $stored_role != $posted_role ) {
    	        wp_set_object_terms( $post_id, $term_ids, 'category' );
    	    }
        }
    }
    add_action('acf/save_post', 'change_post_taxonomy', 20);
    
    • Beee

    • November 22, 2016 at 10:05 pm

    kudos @0000000000
    I had no need yet for a taxonomy with more than 1 allowed option but I bet some people will make good use of it 😉

  • Hi I am trying to get either of the two above examples to work and seem to be failing> I am not sure what is going wrong. This is the code

    function change_post_taxonomy_44582( $post_id ) {
        // bail if no ACF data
        if ( empty($_POST['acf']) ) {
            return;
        }
        // get term id from $post_id (only 1 value is allowed, so it returns 1 value only)
        $stored_role = wp_get_post_terms($post_id, 'asproducts_cats');
        // get submitted value from acf form
        $posted_roles = $_POST['acf']['field_59154e83efb0e'];
        // get term_id for the submitted value
        $term_id    = get_term_by( 'name', $posted_roles, 'asproducts_cats' );
        // if stored value is not equal to posted value, then update terms
        if ( $stored_role != $posted_role ) {
            wp_set_object_terms( $post_id, $term_id->term_id, 'asproducts_cats' );
        }
    }
    add_action('acf/save_post', 'change_post_taxonomy_44582', 20);
    

    Have I done something wrong?

    • Beee

    • May 18, 2017 at 6:35 am

    @mrkeithy it depends on what the output is of $_POST['acf']['field_59154e83efb0e']

    In my case it’s an ID. So look up the options for field ‘field_59154e83efb0e’ and make sure they return IDs and not strings.

  • Thanks for the reply Beee. I might be a bit thick here, but I don’t see options on a radio field to return string or ID. Am I missing something?

    • Beee

    • May 18, 2017 at 8:43 pm

    You have to define your options as “value : label, where value is then your taxonomy id. For example, for Sex I have 3 options:
    1 : Woman
    2 : Man
    3 : Trans
    This returns an id.

    Whereas if you define it like this:
    woman
    man
    trans

    or

    woman : [anything except the word woman]
    man : [anything except the word man]
    trans : [anything except the word trans]

    then it returns a string.

    So it depends on what value $posted_roles is.
    If it’s an ID, you need to change this
    $term_id = get_term_by( 'name', $posted_roles, 'asproducts_cats' );
    to
    $term_id = get_term_by( 'id', $posted_roles, 'asproducts_cats' );

    which should then match your taxonomy id of course.

    So how did you define your options ?

  • Hi Beee

    Sorry its taken me so long to get back to you, got swamped at work then the weekend happened.

    My apologies if I come across a bit thick here. I am not very advanced when it comes to WordPress backend devloping, I am learning as I go.

    In the ACF radio field I have four product types, i.e. Embedded systems, In the product category I have same. I have not used any kind of number system. Is that what I need to do?

    Aga

    • Beee

    • May 22, 2017 at 9:46 pm

    how have you defined you radio options ? With or without the : ?

  • with the :

    • Beee

    • May 22, 2017 at 10:01 pm

    Then your values (left part of : ) need to have the exact name/value as the name of your taxonomy.

  • they do, I copied them over. Should I be using the : ?

    • Beee

    • May 22, 2017 at 10:14 pm

    No…. it’s hard to say without seeing it… I’d love to try and help you more in-depth, outside of this forum, but that means you have to email me your contact info @ berryplasman.com

  • ok, having read through what you have put several times so its clear in my head I have to left of the : put the id of the term, Ie 36 : Embedded Systems. I made the change above to the code to reflect it as ID and it is still not setting the taxonomy on save. So I am now very much lost, is this the way I defined the custom taxonomy?

Viewing 25 posts - 51 through 75 (of 111 total)

You must be logged in to reply to this topic.

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 Cookie Policy. If you continue to use this site, you consent to our use of cookies.