Home › Forums › Backend Issues (wp-admin) › Conditional logic: toggle ACF group based on extension of ACF File field › Reply To: Conditional logic: toggle ACF group based on extension of ACF File field
To show or hide an ACF group based on the extension of a selected file in an ACF File field, you can use a combination of JavaScript and the ACF conditional logic settings. Here’s an example of how you can achieve this:
First, make sure you have the ACF plugin installed and activated.
In your ACF group, add a File field to capture the selected file.
Add a new group that you want to show or hide based on the selected file extension.
In the conditional logic settings for the group you want to show/hide, select “Show this group if” and choose the File field you added in step 2. Set the operator to “Matches regex” and enter the regular expression for the desired file extension. For example, if you want to show the group when a PDF file is selected, use the regex /.pdf$/.
Now, to handle the dynamic show/hide behavior, you can add some custom JavaScript code. Place the following code in your theme’s functions.php file or in a custom JavaScript file:
javascript
(function($) {
$(document).ready(function() {
var fileField = $('#your-file-field-id'); // Replace 'your-file-field-id' with the actual ID of your File field
var groupField = $('#your-group-field-id'); // Replace 'your-group-field-id' with the actual ID of your group field
fileField.on('change', function() {
var fileValue = $(this).val();
var fileExtension = fileValue.substr(fileValue.lastIndexOf('.') + 1);
if (fileExtension === 'pdf') { // Replace 'pdf' with the desired file extension
groupField.show();
} else {
groupField.hide();
}
});
});
})(jQuery);
Make sure to replace ‘your-file-field-id’ with the actual ID of your File field and ‘your-group-field-id’ with the actual ID of your group field.
This code sets up an event listener on the File field. When the selected file changes, it retrieves the file extension and checks if it matches the desired extension (in this case, ‘pdf’). If there’s a match, it shows the group field; otherwise, it hides the group field.
Remember to enqueue the JavaScript file in your theme or plugin to ensure it is loaded on the relevant pages.
With this implementation, the ACF group will dynamically show or hide based on the extension of the selected file in the ACF File field.
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.