Support

Account

Home Forums Add-ons Repeater Field querying database for repeater fields

Solved

querying database for repeater fields

  • hi,

    I’m trying to get values of repeater sub fields filtered by value of another repeater subfield (and am pretty much clueless how to do it)

    example – repeater field group –
    people_types = radio subfield: values – big, medium, small
    ranking_question1 = radio subfield: values 0,1,2,3,4,5
    ranking_question2 = radio subfield: values 0,1,2,3,4,5

    so e.g. i want to find average value for ranking_question1 where people_types = big

    i tried with code below using get_posts but i think $wpdb is way to go (and much faster) . below does not seem work.

    function q_average_byperson( $fieldname, $people_type, $posttype) {
    
    $posts = get_posts(array(
    	'numberposts' => -1,
    	'post_type' => $posttype
    
    ));
    
    $total = 0;
    $counter = 0;
    
    if($posts)
    	{
    	 
    		foreach($posts as $post)
    		{
            if(get_field('values_and_outcomes'))
    {
     
    	while(has_sub_field('values_and_outcomes'))
    	{
    		if (get_sub_field('people_type') == $people_type)
    		{
    		$total = $total + get_sub_field($fieldname);
    		$counter++;
    	    }
    	}
    }
    
    	}
    $paverage = $total / $counter;
    $average = round($paverage, 1);	
    	}
    return $average;
    }

    any and all ideas, or pointers much appreciated

    thanks
    ian

  • Hi @silverdarling

    Your code looks fine to me. Have you attempted to debug it to find out why ‘it isnt working’?

    Thanks
    E

  • working now thanks.

    Using ACF functions within get_posts (and maybe all functions?) means there has to be an explicit post ID passed to the ACF functions, so above works if $post->ID added

    eg

    if(get_field('values_and_outcomes', $post->ID))
    
    while(has_sub_field('values_and_outcomes', $post->ID))
    
    get_sub_field($fieldname, $post->ID) 

    etc

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘querying database for repeater fields’ is closed to new replies.