Support

Account

Home Forums Backend Issues (wp-admin) get_field inside an acf/load_value function

Solved

get_field inside an acf/load_value function

  • I have around 20 fields in a CPT. I’d like to fill them with data from fields in another post type.

    The straightforward case is like this:

    
    function load_my_values( $value ) {
    		$new_value = get_field( 'other_field', $POST_ID) );
    		return $new_value;
    };
    add_filter( 'acf/load_value/name=example_field', 'load_my_values' );
    

    But this has 2 problems: I don’t have access to $POST_ID (probably can be worked out), and I need to write 20 functions and 20 add_filter lines (and more to come in future).

    So I thought to write a general function like this:

    
    function load_my_values( $value, $post_id, $field ) {
    
      // There's a 'post_selection' field in the current CPT that contains the id of 
      // the other CPT post. And the value is already saved - no ajax stuff needed. 
      $other_cpt_id = get_field( 'post_selection' );
      
      switch ( $field['name'] ) {
    			case 'example_field':
    				$new_value = get_field( 'other_field', 'posttype_' . $other_cpt_id );
    				break;
          case 'another_example_field':
      			$new_value = get_field( 'other_other_field', 'posttype_' . $other_cpt_id );
      			break;
          // etc
    		}
    		return $new_value;
    };
    add_filter( 'acf/load_value', 'load_my_values', 10, 3 );
    

    This crashes my server. I believe it’s because using get_field calls the filter recursively.

    Is there a way around this? Some way to skip acf/load_value while inside my function?

  • Yes, you are creating an infinite loop because this $other_cpt_id = get_field( 'post_selection' ); causes your filter to be called every time your filter runs.

    At the beginning of your filter add

    
    remove_filter( 'acf/load_value', 'load_my_values', 10, 3 );
    

    and then at the end of your filter re-add

    
    add_filter( 'acf/load_value', 'load_my_values', 10, 3 );
    
  • Thanks! Your solution would be ideal for most people.

    Unfortunately, remove_action isn’t available to me, because I’m using Tom McFarlin’s WordPress Plugin Boilerplate. (add_action/filter become methods, no equivalent for remove). Adding a remove_action has been discussed for several years but not implemented.

    This fork of WPPB adds a remove method.

    However in the end, I implemented a separate filter just for post title, on wp_insert_post_data, which sets a value for $data['post_title'].

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

The topic ‘get_field inside an acf/load_value function’ is closed to new replies.