Filter Pages by Custom Field (ACF) in admin area

I’m trying to filter pages in admin area by a custom field created with ACF.

I found a function here ( http://www.iamabdus.com/blog/wordpress/filter-custom-posts-by-custom-field/ ) and I adapted that code to my need.

When I click on “pages” the options load correctly, but when I click on “Filter” even if the filter work good, I receive a Warning: “Invalid argument supplied for foreach()”.
The var_dump($acf_field) return NULL.

I hope I explained the problem…

Here is the code:

add_action( ‘restrict_manage_posts’, ‘wpse45436_admin_posts_filter_restrict_manage_posts’ );

function wpse45436_admin_posts_filter_restrict_manage_posts(){
$acf_field_name=’field_5c65759c23c46′;
$acf_field=get_field_object($acf_field_name);
var_dump($acf_field);
$post_type_to_filter=’page’;
$type = ‘post’;

if (isset($_GET[‘post_type’])):
$type = $_GET[‘post_type’];
endif; // isset($_GET[‘post_type’])

if ($post_type_to_filter == $type):
foreach($acf_field[‘choices’] as $field_value => $field_label){
$values[$field_label]=$field_value;
}
?>
<select name=”custom_field_filter_value”>
<option value=””>Filtra per tipo pagina</option>
<?php $current_v = isset($_GET[‘custom_field_filter_value’])? $_GET[‘custom_field_filter_value’]:”;
foreach ($values as $label => $value) :
printf(
‘<option value=”%s”%s>%s</option>’,
$value,
$value == $current_v? ‘ selected=”selected”‘:”,
$label
);
endforeach;
?>
</select>
<?php
endif;
}

add_filter( ‘parse_query’, ‘wpse45436_posts_filter’ );
function wpse45436_posts_filter( $query ){
global $pagenow;
$type = ‘post’;
if (isset($_GET[‘post_type’])):
$type = $_GET[‘post_type’];
endif;
$query->query_vars[‘meta_value’] = $_GET[‘custom_field_filter_value’];
}

Read more here:: Filter Pages by Custom Field (ACF) in admin area

Leave a Reply

Your email address will not be published. Required fields are marked *