Prince Bhati
Prince Bhati

Reputation: 105

Writing a php function for advance custom field in wordpress

I want to implement a progress bar using elementor for WordPress website, for that I've used the widget progress bar, but I'm adding the percentage value dynamically in the progress value, for that I've created a field percentage in my Campaign Details group field in Advance custom field plugin, which have type number and added it to the dynamic tag in progress bar.

After that I've added my php code in snipped code, I'm new to php, so don't know why it is incorrect, I did take the help of chatgpt other sources to find the mistake.

I've wrote two types of function, in the first type, I've used the array to access the campaign details group field to access its fields and in another I've used this notation: get_field('group_field_name_subfield_name')

first type

function calculate_donation_percentage($post_id) {
    $donation_received = get_field('Campaign Details', $post_id)['donation_received'];
    $donation_required = get_field('Campaign Details', $post_id)['donation_required'];

    if ($donation_required == 0) {
        $percentage = 0;
    } else {
        $percentage = ($donation_received / $donation_required) * 100;
    }

    update_field('Campaign Details', array('donation_percentage'=> $percentage), $post_id);
}
add_action('save_post', 'calculate_donation_percentage');

second type

function calculate_donation_percentage($post_id) {
    $donation_received = get_field('Campaign Details_donation_received', $post_id);
    $donation_required = get_field('Campaign Details_donation_required', $post_id);

    if ($donation_required == 0) {
        $percentage = 0;
    } else {
        $percentage = ($donation_received / $donation_required) * 100;
    }

    update_field('Campaign Details_donation_percentage', $percentage, $post_id);
}
add_action('save_post', 'calculate_donation_percentage');

I've read that we can add filter method too to add the value into acf field.

add_filter('acf/update_value/key=campaign_details_donation_percentage', 'calculate_donation_percentage', 10, 3);

Please give me some ideas about how I solve this problem. it is image of acf fields which i've created

Upvotes: 0

Views: 87

Answers (1)

Asiqur Rahman
Asiqur Rahman

Reputation: 431

In first type, I think you typed the wrong field ID 'Campaign Details', IDs does not contain space, check your acf dashboard to find the right field ID, check the attached image.

enter image description here

Upvotes: 1

Related Questions