Support

Account

Home Forums Backend Issues (wp-admin) How can I register fields via php when a post is saved

Helping

How can I register fields via php when a post is saved

  • Hey,

    my question seems to be very simple and I have many ideas how to solve it but maybe I understand something wrong. Please help me!

    I want to register new fields via php in the admin area for lets say a post of type “test_type_1”. If I use the following code in the functions.php it works like a charm:

    if( function_exists('acf_add_local_field_group') ):
    
    acf_add_local_field_group(array(
    	'key' => 'group_1',
    	'title' => 'My Group',
    	'fields' => array (
    		array (
    			'key' => 'field_1',
    			'label' => 'Sub Title',
    			'name' => 'sub_title',
    			'type' => 'text',
    		)
    	),
    	'location' => array (
    		array (
    			array (
    				'param' => 'post_type',
    				'operator' => '==',
    				'value' => 'test_type_1',
    			),
    		),
    	),
    ));
    
    endif;

    Okay! So what I am trying next is to change the group_label. Let’s say for testings I want to change it in a way that there is the current shown post_title appended or a linked acf-field title or something else.

    Here is the point it doesn’t work anymore! I cant add new fields by code when I cange the parameters in the code above by getting other field values. Like this for example:

    From:
    'label' => 'Sub Title',

    To:
    'label' => get_queried_object()->post_title,

    My target is to generate new fields via php in posts of the type “test_type_1”. These new fields shall represent all posts of “test_type_2” I linked this post to.

    I hope you can give me some hints to solve this problem! 🙂

  • When you are registering the fields in when you call acf_add_local_field_group() you need to get the value that was previously saved.

    
    if( function_exists('acf_add_local_field_group') ):
    
    $label = 'Default Label';
    // code to do something like get a new field label will go here
    // what you need to do depends on where you're saving the
    // value that you want to use
    
    acf_add_local_field_group(array(
    	'key' => 'group_1',
    	'title' => 'My Group',
    	'fields' => array (
    		array (
    			'key' => 'field_1',
    			'label' => $label,
    			'name' => 'sub_title',
    			'type' => 'text',
    		)
    	),
    	'location' => array (
    		array (
    			array (
    				'param' => 'post_type',
    				'operator' => '==',
    				'value' => 'test_type_1',
    			),
    		),
    	),
    ));
    
    endif;
    
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘How can I register fields via php when a post is saved’ is closed to new replies.