500 Server Error with WP User Query/ACF data comparison
-
Hello, I’ve recently implemented a WP User Query based system for showing and filtering users of a specific role at the website I have linked. I’m using ACF to store data about each user, and using a form to submit different WP User Query arguments via an Ajax call to filter the results. Where I’m having the problem is specifically with my dynamically populated form filter options. I started by writing some plugin code to pull all available options from the ACF field object I wanted to create the filter options from, and output them as styled checkboxes for the user to select during a search via a shortcode function. That worked fine. However, when I tried to improve the code to compare those field object values with options from that object that have been chosen by actual users and then ONLY output options from that ACF object that have been chosen at least once by a user, my plugin causes a 500 error to occur on the page it is inserted. I’ve poured over my code and there doesn’t seem to be anything inherently wrong with it’s logic? Thanks in advance for anyone willing to give a fresh set of eyes.
<?php
// Query to retrieve users where the ACF field is not empty
$user_query = new WP_User_Query(array(
'meta_query' => array(
array(
'key' => 'designations', // Replace with your ACF field name
'compare' => 'EXISTS', // Check if the field exists
),
),
));
// Check if users were found
if (!empty($user_query->results)) {
$all_chosen_values = array(); // Array to store all chosen values
// Loop through the users
foreach ($user_query->results as $user) {
// Get the values of the ACF field for the user (assuming it's an array)
$values = get_user_meta($user->ID, 'designations', true); // Replace with your ACF field name
// Check if values is an array
if (is_array($values)) {
// Merge values into the all_chosen_values array
$all_chosen_values = array_merge($all_chosen_values, $values);
}
}
// Remove duplicates
$all_chosen_values = array_unique($all_chosen_values);
// Get the field object
$field = get_field_object('field_664517d942b6e'); // Replace with ACF field name
if ($field) {
// Output the chosen values as checkboxes
foreach ($all_chosen_values as $value) {
if (array_key_exists($value, $field['choices'])) {
echo '<div class="form-checkbox-option"><input type="checkbox" id="' . esc_attr($value) . '" name="designations" value="' . esc_attr($value) . '">';
echo '<label for="' . esc_attr($value) . '">' . esc_html($field['choices'][$value]) . '</label></div>';
}
}
}
}
?>The page I need help with: [log in to see the link]
- You must be logged in to reply to this topic.