Support

Account

Home Forums General Issues Merge multiple fields value to one

Solved

Merge multiple fields value to one

  • Hi,

    first of all I would like to thank you for this great plugin.

    I would like to ask, if there is 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”.

    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)

  • This code is un-tested as of now, but your best bet would be to use the acf/save_post hook, most likely:

    function merge_post_values($post_id) {
        if (empty($_POST['acf'])) {
            return;
        }
    
        // Run some logic to determine whether or not the current post is
        // correct -- for example, based on the ID, template, post type, etc.
        if ($post_id == 1) {
            $merged_values = [];
    
            if (isset($_POST['value_1'])) {
                $merged_values[] = $_POST['value_1'];
            }
    
            if (isset($_POST['value_2'])) {
                $merged_values[] = $_POST['value_2'];
            }
    
            update_post_meta($post_id, 'merged_values', $merged_values);
        }
    }
    
    add_action('acf/save_post', 'merge_post_values', 1);

    I’ve not included any sanitation and I’m not entirely sure how your structure is setup (for example, if the values are strings, arrays, so on), or how they need to be saved, but the above should be enough of a premise to work on for saving the values as a separate piece of post meta.

  • I did not manage to get it working, but I`m not very advanced.

    I`ve put it in the functions.php, changed the values to real acf fields (all of them are set to output values) – created the final “merged_values” field as a text field, but after publishing the result field stays empty.

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

The topic ‘Merge multiple fields value to one’ is closed to new replies.