Support

Account

Home Forums Add-ons Repeater Field Dynamically add rows to repeater field on post load

Solved

Dynamically add rows to repeater field on post load

  • Hi,

    I use CPT’s and I would like to dynamically load its categories into rows in a repeater field.

    Here’s what I have so far:

    function acf_load_taxonomy_custom_urls_table( $field ){
    		
    	$categories = get_the_terms(get_the_ID(), 'category');
    	
    	foreach ($categories as $category){
    		
    		echo("<script>console.log('PHP: " . $category->term_id . "');</script>");
    		
    		$row = array(
    			'field_5b1d513f4bc65' => $category->name,
    			'field_5b1d51a24bc66' => '',
    			'field_5b1d51e74bc67' => '',
    		);
    				
    		add_row($field, $row, get_the_ID());
    		
    	}
    		
    	return($field);
    		
    }
    
    add_filter('acf/load_field/key=field_5b1d50cf4bc64', 'acf_load_taxonomy_custom_urls_table');

    The code outputs the category term_id in the JS console, so it’s definitely loading the right categories. However, no rows are added to the repeater field. Can someone help me out?

    Using ACF Pro 5.6.10 btw.

    Thanks in advance!

    Jacco

  • You’re trying to use acf/load_field filter and you should probably be using the acf/load_value filter, something like this

    
    function acf_load_taxonomy_custom_urls_table($value, $post_id, $field){
    		
    	$categories = get_the_terms($post_id, 'category');
    	
    	foreach ($categories as $category){
    		
    		echo("<script>console.log('PHP: " . $category->term_id . "');</script>");
    		
    		$value[] = array(
    			'field_5b1d513f4bc65' => $category->name,
    			'field_5b1d51a24bc66' => '',
    			'field_5b1d51e74bc67' => '',
    		);
    		
    	}
    		
    	return $value;
    		
    }
    
    add_filter('acf/load_value/key=field_5b1d50cf4bc64', 'acf_load_taxonomy_custom_urls_table', 20, 3);
    

    Your main problem here is going to be that your categories will be added every time you save and the post refreshes, adding the same values over and over again. What you’ll need to do it to loop over the existing value and make sure each value does not already exist before adding a new row. And then there is the fact that any values deleted will not be deleted unless you also test to see if any categories have been removed and removes those rows from the repeater array.

  • Hi John,

    Thanks! This is what I was looking for 🙂 As for the other problems: I already figured that this would not be a complete solution, but at least I am a step closer.

    Thanks again!

    Jacco

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

The topic ‘Dynamically add rows to repeater field on post load’ is closed to new replies.