I’m using Advanced Custom Fields / ACF to create custom fields. One of them is a list of checkboxes that display some options (option1, option2, option3…).
Now I want to display all options of this field on a separate page on the frontend like so:
Options:
– option 1
– option 2
– option 3
– …
How can I retrieve all options with keys from ACF?
The
get_field_object
ACF function can be used to get info and options for a specific field.First you need the field key of the specific field you wish to output. When editing a field group, click on the screen options tab at the top of the page. You should see an option to toggle the display of the field key (it is hidden by default to save space):
Once you have the key, you can load the field object and output its values:
If you’re trying to output something if a checkbox was checked, use:
If you’re trying to just display a list of the checked options, use this:
This will give you an array of values that you can manage with a
foreach
declaration. Usingthe_field('checkbox')
will give you a comma separated string of the options that you can split up as well.I would also suggest you go to ACF’s site and go through the documentation. Most questions of this type will be answered there in decent detail, and the developer is active in his support forums as well.
EDIT: If you’re wanting the list of available options output into a page for generating a dynamic query, I have just the thing. This is a piece I just built out yesterday for pulling a list of meta values from a given custom field key (using ACF). I’ve made it fairly generic for you. There’s another chunk of JS for handling the ajax request, and a rather convoluted piece of php that outputs the resulting posts. I can’t really rewrite those – the JS is standard WP forward-facing ajax call/response, and the PHP is a mess of conditional checks for the 12 different ACF fields we’re displaying (2 of which are repeaters). The basics are this code here, the button
onClick
calls the ajax function in a separate JS file, and the php for the ajax function itself essentially sets up an array of arguments for the query, one of which is$selectedOption
or$_POST['option']
as meta_value. That gets fed to anew WP_Query( $args );
, which is then used in a loop, the output of which gets fed back to the js viaadd_action('wp_ajax_the_ajax_hook', 'fetch_option_list');
andadd_action( 'wp_ajax_nopriv_the_ajax_hook', 'fetch_option_list' ); //for non logged-in users
.