advanced-custom-fieldsacfpro

Problem with autopopulate of an ACF field when a value already exists


I have the following scenario:

(a) Existing posts created with Avada Theme Builder. Here everything (layout and content) is stored in the same post and can only be changed manually per post;

b) Existing posts created via a custom backend. The individual fields are output via a global layout from the ATB.

c) New posts, which are created via the new backend.

If I now try to filter out the corresponding data and fill in the fields in the backend, this only works partially.

This is now an example code, which I use for different fields:

// Import data for field "Domainname"
function load_domainname($value, $post_id, $field) {
    if (get_field('new_backend', $post_id) != 1 && get_post_status($post_id) == 'publish') {
        if (get_field('domain', $post_id)) {
            return get_field('domain', $post_id);
        } else {
            return get_the_title();
        }
    }
}
add_filter('acf/load_value/name=domainname', 'load_domainname', 10, 3);

If I have scenario A and want to edit A, the fields are filled in correctly.

If I have scenario C, then no fields are filled in - which is also correct, since nothing is available.

But if I have scenario B, then the corresponding field is emptied. The existing entry is then no longer present.

All attempts to query beforehand whether the field to be filled in already has a value end in a fatal error.

Example:

// Import data for field "Domainname"
function load_domainname($value, $post_id, $field) {
    $domain = get_field('domainname', $post_id);
    if ($domain == '') {
        if (get_field('new_backend', $post_id) != 1 && get_post_status($post_id) == 'publish') {
            if (get_field('domain', $post_id)) {
                return get_field('domain', $post_id);
            } else {
                return get_the_title();
            }
        }
    }
}
add_filter('acf/load_value/name=domainname', 'load_domainname', 10, 3);

Does anyone have a solution for this problem?


Solution

  • My mistake, forgot to return the original value after the IF statement.

    // Import data for field "Domainname"
    function load_review_domainname($value, $post_id, $field) {
        if (has_tag('it', $post_id) == false && get_post_status($post_id) == 'publish') {
            if (get_field('domainname', $post_id)) {
                return get_field('domainname', $post_id);
            } else {
                return get_the_title();
            }
        }
        return $value;
    }
    add_filter('acf/load_value/name=review_domainname', 'load_review_domainname', 10, 3);