I have the following code to populate checkbox fields in a gravity form.
I have an array of field_ids I'm looping through with a foreach loop.
$arr = array(5, 6, 7, 8, 9);
I then have a second foreach loop with a query which is pulling data from the database.
The code is working however, each subsequent field_id is showing the results for that field_id AND the previous ones. eg field_id=6 is showing a list of checkbox fields for field_id=5 and field_id=6. field_id= 7 is showing a list of checkbox fields for field_id=5, field_id=6 and field_id=7 etc.
function populate_checkboxes( $form ){
foreach( $form['fields'] as &$field ) {
$arr = array(5, 6, 7, 8, 9);
foreach($arr as $field_id){
global $wpdb;
$query = $wpdb->get_results( "SELECT sefer FROM bulk_import where field_id_select_items = {$field_id}" );
foreach($query as $sefer){
if ( $field->id != $field_id ) {continue;}
$choices[] = array( 'text' => 'Select All', 'value' => 'Select_all' );
$inputs[] = array( 'label' => 'Select All', 'id' => '1');
//get all $sefer values
$posts = get_posts(array(
'post_type'=> array('learning_item'), 'suppress_filters' => 0, 'posts_per_page' => -1, 'order' => 'asc',
'meta_query' => array(
array( 'key' => 'taken', 'value' => '0'),
array('key' => 'torah', 'value' => $sefer -> sefer)
),
));
$input_id = 2;
foreach( $posts as $post ) {
//skipping index that are multiples of 10 (multiples of 10 create problems as the input IDs)
if ( $input_id % 10 == 0 ) {$input_id++;}
$choices[] = array( 'text' => $post->post_title, 'value' => $post->post_title );
$inputs[] = array( 'label' => $post->post_title, 'id' => "{$field_id}.{$input_id}" );
$input_id++;
}
$field->choices = $choices;
$field->inputs = $inputs;
}
//reset query here?
wp_reset_query();
}
}
return $form;}
Do I need to reset the query somewhere? I tried to add wp_reset_query(); in a few different places but it didn't work. Where do I need to reset the query?
wp_reset_query()
restores the$wp_query
and global post data to the original main query. In the code snippet provided, you did not touch$wp_query
or the main query. Thus, you don't need to reset your query. Your issue is elsewhere, but I can't pinpoint it. It read to me like a variable was not cleared (set to empty) before reusing it in the loop again, that would cause the carrying over of previous-data.