Filter by a Custom Field in a Custom Post Type on Admin Page with ACF

If you’re trying to create a filter using restrict_manage_posts and the Advanced Custom Fields WordPress (ACF Pro) plugin then you’ve probably run into a problem where the get_field_object & get_acf_field functions work BEFORE you filter, but not AFTER you filter.

The get_field_object & get_acf_field & acf_get_field don’t work with restrict_manage_posts

The documentation says this should work, but it flat out doesn’t. So I programmed a solution to help anyone else trying to figure this out since there were no other guides online.

Using ACF get_field functions in manage_workorder_posts_custom_column

The same thing happens inside manage_workorder_posts_custom_column, and the below function will work there as well.

Get ACF Field Choices

You can use this function exactly like get_acf_field() as it returns the same values. You can also use it to get the field’s choices.

You must use the Field ID. You can’t use the Field Name.

$field_object = get_acf_field_wpdb(‘field_id_here’); // contractor_crew
$field_choices = $field_object[‘choices’];

/**
 * Function to get the ACF field from the database using $wpdb
 * This is necessary because the get_acf_field() function doesn't work after filtering
 * If custom options are provided during restrict_manage_posts get_acf_field() doesn't work. 
 * It DOES work if no filtering is done.
 */
function get_acf_field_wpdb($field_name = null) {
    
	if (empty($field_name)) { return []; }
	
	global $wpdb;

    // Prepare the query to search for the ACF field
    $query = $wpdb->prepare(
        "SELECT post_content FROM {$wpdb->posts} WHERE post_type = 'acf-field' AND post_name = %s",
        $field_name
    );

    // Execute the query
    $results = $wpdb->get_results($query);

    // Check if results are not empty and return the first element
    if (!empty($results)) {
        return maybe_unserialize($results[0]->post_content);
    }

    return [];
}