Search code examples
wordpressadvanced-custom-fields

Wordpress/ACF merging multiple fields value to one


Is there any way to get values from multiple fields (for example: “value_1”, “value_2”, etc.) and merge all of them to a new field, let`s say “merged_values” after publishing/editing the post?

Something like this:

If:

value_1 = red blue; value_2 = gold silver;

Then:

merged_values = red blue gold silver;

I need to achieve this, because of a search plugin, that doesn`t show the results if the search query is “red silver” and there is no option in it to combine the search within multiple ACF fields.

(to be exact, I need the “merged_values” field to be written in the db as the example above – not just echo the values together in the front-end).

The output from the default fields is pure text with spaces and the "merged_values" should also be just pure text (no arrays, etc.)


Solution

  • I think you want something like this

    // This function runs after your post is saved
    function my_acf_save_post( $post_id ) {
    
        // Get new value of field 1
        $value1 = get_field( 'field1', $post_id );
    
        // Get new value of field 2 
        $value2 = get_field( 'field2', $post_id );
    
        // Merged values with ; on the end
        $merge = implode(" ",$value1).' '.implode(" ",$value2);
    
        // Update field 3 with the new value which should be
        // value1 value2;
        update_field( 'field3', $merge, $post_id );
    }
    add_action('acf/save_post', 'my_acf_save_post', 20);
    

    I'm not sure if you wanted to put the merged value in another ACF field. If not you can use $wpdb to insert it in de database manually.