Filter an Admin List by an ACF Select Field
Adds a dropdown above a post type's admin list to show only posts with a chosen value of an ACF select, radio or button group field.
Opens WPIDE on
Code
// Post type and choice field name.
$wpide_acf_filter_type = 'post';
$wpide_acf_filter_field = 'status_label';
add_action( 'restrict_manage_posts', function ( $post_type ) use ( $wpide_acf_filter_type, $wpide_acf_filter_field ) {
if ( $wpide_acf_filter_type !== $post_type || ! function_exists( 'acf_get_field' ) ) {
return;
}
$field = acf_get_field( $wpide_acf_filter_field );
if ( ! $field || empty( $field['choices'] ) ) {
return;
}
$current = isset( $_GET['acf_filter'] ) ? sanitize_text_field( wp_unslash( $_GET['acf_filter'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
echo '<label class="screen-reader-text" for="acf-filter">' . esc_html( $field['label'] ) . '</label><select name="acf_filter" id="acf-filter"><option value="">All ' . esc_html( strtolower( $field['label'] ) ) . '</option>';
foreach ( $field['choices'] as $value => $label ) {
printf( '<option value="%s"%s>%s</option>', esc_attr( $value ), selected( $current, (string) $value, false ), esc_html( $label ) );
}
echo '</select>';
} );
add_action( 'pre_get_posts', function ( $query ) use ( $wpide_acf_filter_type, $wpide_acf_filter_field ) {
if ( ! is_admin() || ! $query->is_main_query() || $wpide_acf_filter_type !== $query->get( 'post_type' ) || empty( $_GET['acf_filter'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
return;
}
$meta_query = (array) $query->get( 'meta_query' );
$meta_query[] = array(
'key' => $wpide_acf_filter_field,
'value' => sanitize_text_field( wp_unslash( $_GET['acf_filter'] ) ), // phpcs:ignore WordPress.Security.NonceVerification
);
$query->set( 'meta_query', $meta_query );
} );
Notes
Set the post type and field name. The choices come from the field's own settings.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.