Last active
April 30, 2017 15:59
-
-
Save chrismcintosh/a51b474bdd572a0b2390ade1345a40da to your computer and use it in GitHub Desktop.
Some boilerplate code for populating an ACF select box with custom taxonomies and then querying a custom post type using the result of that select box.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Assumes a custom post type called 'staff' | |
Assumes that there is a custom taxonomy called 'department'. | |
Every department that has at least one staff member assigned to it will | |
populate a select field that is specified in Advanced Custom Fields. | |
Using that Select field we can then do a query on a custom post type | |
in this case staff and grab only the staff with our selected department. | |
*/ | |
// Part 1 | |
// Place this filter in functions.php or another file of your choosing depending on project structure | |
// This filter uses the field key, for other options | |
// check the ACF docs here -> https://www.advancedcustomfields.com/resources/acfload_field/ | |
add_filter('acf/load_field/key=field_58b064ec5de3d', 'sby_department_acf_select'); | |
function sby_department_acf_select( $field ) { | |
$departments = get_terms( array( | |
'taxonomy' => 'department', | |
'orderby' => 'name', | |
) ); | |
foreach($departments as $department) { | |
$field['choices'][$department->slug] = $department->name; | |
} | |
return $field; | |
} | |
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Part 2 | |
// Place the following code where you want to do a query | |
// Assumes that this is in a flexible content custom field | |
$selected_department = get_sub_field('department'); | |
$args = array( | |
'post_type' => 'staff', | |
'posts_per_page' => -1, | |
'tax_query' => array( | |
array( | |
'taxonomy' => 'department', | |
'field' => 'slug', | |
'terms' => $selected_department | |
) | |
) | |
); | |
$loop = new WP_Query( $args ); | |
while ( $loop->have_posts() ) : $loop->the_post(); | |
the_title(); | |
endwhile; | |
/* Reset the post data because of our custom query */ | |
wp_reset_postdata(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you, nice job!