If you tried to set conditional logic using Advanced Custom Fields plugin, but haven’t done it before, there’s a chance that you will stumble upon the following message “No toggle fields available” wondering what that means. Fortunately, it is very easy to set this up. In order to add toggle fields, you would only need to create a new custom field of “choice” Field Type and add few Choices.
For this particular example, I used “Select” choice, creating select custom field type. Into Choices, let’s add few options:
- none
- first choice
- second choice
The third step is to create few custom fields and attach the conditional logic on them. It isn’t important at this point what kind of fields do we have, as it could be anything. You could set one custom field to show the post URL, and the other one to show custom URL.
But how would you display custom fields depending on the choice being made? As you probably know, the_field() will display custom field value, but we can also find some use of get_field() here. This is how we could write the PHP function:
1 2 3 4 5 6 7 8 9 10 |
<?php if ( 'none' == get_field('custom_url_toggle')){ //do nothing } elseif ( 'first choice' == get_field('custom_url_toggle') ) { the_field("custom_url"); } elseif ( 'second choice' == get_field('custom_url_toggle') ) { the_field("regular_url"); } ?> |
This function will display nothing if “none” is selected, it will display the content of custom_url field if “first choice”is selected and regular_url value if the “second choice”is selected.