Support

Account

Home Forums Search Search Results for 'update_field save value'

Search Results for 'update_field save value'

topic

  • Solving

    Repeater field returning row count instead of array

    Hi

    So I’m working with a repeater field, and API response data, and I’m trying to programatically create repeater rows from my API response data and I’m having some weird issues. I’ve tried many different approaches and it kind of works, but i can’t display my data on the frontend correctly.

    This is my function to set the repeater data:

    private function updateTicketsField($post_id, $item) : void
        {
            $tickets = [];
            $i = 0;
            if (isset($item['rate']['event'][0])) {
                foreach ($item['rate']['event'][0] as $type => $details) {
                    if (isset($details['amount'])) {
                        $tickets[$i]['type'] = ucfirst($type);
                        $tickets[$i]['price'] = floatval($details['amount']);
                        $i++;
                    }
                }
            }
            update_field('tickets', $tickets, $post_id);
        }

    This function is being fired on the save_post action:

    add_action('save_post', [$this, 'saveFields'], 10, 3);

    saveFields is just a parent function, but this calls updateTicketsField(), $item is the API response data as an array.

    So what’s weird about it, is that the Data is actually being saved against the post / in the database correctly. When i go to the Admin for the post i can see the Repeater rows have been added correctly.

    What i have discovered is that for some reason in the database the Row count is being saved under the key:

    “meta_id” “post_id” “meta_key” “meta_value”
    “14193” “105” “tickets” “2”
    “14194” “105” “_tickets” “field_676293d3f9427”

    But because of this whenever i try to do:

    $tickets = get_field('tickets', $id);

    It returns as the row count “2”, instead of the array of data / sub fields.

    Or if i instead do:
    if (have_rows('tickets', $id)) this seems to return as a false value.

    So things I’ve tried:

    Instead of using update_field() with the field names I’ve tried using field keys:

    $tickets[$i]['field_67c82f43a270c'] = ucfirst($type);
    $tickets[$i]['field_67c82f56a270d'] = floatval($details['amount']);

    update_field('field_676293d3f9427', $tickets, $post_id);

    But the same problem persists.

    I’ve also tried using add_row() instead of update_field:

    add_row('tickets', [
    
                         'type' => ucfirst($type),
    
                        'price' => floatval($details['amount']),
    
    ], $post_id);

    But again this has the same issue.

    Between each test I’ve been manually deleting the data directly from the database. and I’ve also used:

    wp_cache_flush();
    delete_post_meta($id, 'tickets');
    delete_post_meta($id, '_tickets');

    to cleanup any rogue values which might be hanging around.

    Oddly enough I’ve tried commenting out the ‘save_post’ filter entirely, and just adding my repeater row data in manually, but it still seems to have the same issue. Even if i delete the Fields and recreate them within the Field Group.

    I’m a bit stuck with this so any help would be appreciated.

  • Solved

    Add row and type fields on the Flexible Content Field when I save

    Hello.

    I have configured the Flexible Content Field as follows:

    Field Type: Flexible Content
    Field Name: cf_person (Key: field_xxxxxxx)

    Layout
    Name: cf_person_set

    Fields:
    Name: cf_person_text_ja (Key: field_yyyyyy)
    Type: WYSIWYG Editor

    I want to add a new row to the flexible content and set the value of “cf_person_text_ja” to “Dummy Text” when I save a post.
    I want to do this in the functions.php file.

    The following code doesn’t work:

    
    function publish_post_transition_person($post_ID) {
    
      $row = [
        'cf_person_text_ja' => 'Dummy Text',
      ];
    
      update_field('cf_person_set', $row, $post_ID);
    
      return false;
    
    }
    
    add_action( 'save_post', 'publish_post_transition_person' );
    
    
  • Helping

    Can’t read data from ACF during import with WP All Import

    Can’t read data from ACF during import with WP All Import

    Hey everyone,

    First of all, I already asked the WP All Import Pro Support to help me but they had no idea and they “do not give any support to custom code”. So I really hope I can get some help here.

    I am importing a .csv file with products to my WooCommerce shop and I have a custom function that saves a json string to an acf field. (I have to save pairs of sizes for a products with a unique url for each size.)

    This is pretty straight forward and saving a string to the field works just fine but I do not get any value when I try to read from the same ACF Field so at the end of the import I only have the latest size/url pair in the json string saved.

    I tried to use get_field as well as get_post_meta, but it’s the same problem with both functions – no data.

    I am almost sure that it did work a couple of weeks ago when I first wrote the script but some update broke it and I have no idea how to fix it rn.

    Here is the code:

    <?php
    function update_product_sizes($post_id, $data ) {
    
        // The current data row from the imported .csv
        $row = json_decode(json_encode((array) $data), true);
        $size = $row["size"];
        $affiliate_url = $row["link"];
        $product_name = $row["title"];
    
        // Der ACF Field Key mit den Daten Groesse und URL
        $field_key = "field_6628d713e57dd"; // Replace with the actual field key for your ACF field
    
        // Step 1: Retrieve the ACF field value (JSON data)
        $json_data = get_field($field_key, $post_id);
        //$json_data = get_post_meta($post_id,$field_key,true);
    
        ob_start();
        print_r($json_data);
        $output = ob_get_clean();
    
        add_log_msg("Retreived ACF Data: " . $output . ", PostID: " . $post_id . "<br />");
    
        // Step 2: Decode the JSON data into a PHP array
        $data_array = $json_data ? json_decode($json_data, true) : array();
    
        // Step 3: Define the new size and URL to be added
        $new_entry = array(
            'size' => $size,  // size
            'url' => $affiliate_url  // Affiliate URL
        );
    
        // Step 4: Add the new entry to the array
        $data_array[] = $new_entry;
    
        // Step 5: Encode the PHP array back to JSON
        $new_json_data = json_encode($data_array);
    
        // Step 6: Update the field with the new JSON data
        $update = update_field($field_key, $new_json_data, $post_id);
    
        if($update) {
            $log_msg = "New Size and URL added for product: " . $product_name . ", Size: ". $size .", URL: ". $affiliate_url . ", data: ". $new_json_data . ", post ID: ". $post_id . ", Field Key: ". $field_key . "<br/>";
            add_log_msg($log_msg);        
        } else {
            $log_msg = "Update failed.";
            add_log_msg($log_msg);    
        }
    
    }
    
    // Hook into WP All Import
    add_action('pmxi_saved_post', 'update_product_sizes', 10, 2);
    
    function add_log_msg($m) {
        printf("[%s] %s", date("H:i:s"), $m);
        flush();
    }
    
    ?>

    Any help or hints on what to try is very much appreciated. Thanks!

  • Unread

    update_field on newly created taxonomy term

    Hi. I am trying to set a field value on a custom taxonomy term, which may be newly created. Here’s my logic:

    $client_term = get_term_by( 'name', $contact['name'], 'mp_client' );
    if ( !$client_term ) {
        $client_term = wp_insert_term( $contact['name'], 'mp_client' );
    }
    update_field( 'contact_id', $contact['id'], 'mp_client_' . $client_term->term_id );

    For some reason, update_field doesn’t save the value when the term is newly created by wp_insert_term. For existing terms, it works.
    Why is that? I’ve tried saving using field_keys, but it makes no difference.

  • Solving

    Update_field for multiple Posts using one sql query

    I update around 300 posts a few times a week with a process similar to this:

    $schools = get_schools_object_from_csv($file_path);
    
    foreach ($schools as $id => $school_data) {
      $post_id = get_post_id_by_school_id($id);
      if (empty($post_id)) {
        $post_id = wp_insert_post( [...$school_data[stuffToCreatePost]] );
        update_field('programs', $data['programs'], $post_id);
      } else {
          update_field('programs', $data['programs'], $post_id);
      }
    }

    These schools are sometimes existing schools (a post already exists) where we need to update the school’s programs: an ACF repeater, or it’s a new school where I need to wp_insert_post and then I add the programs to that post.

    This process takes around 1 minute for around 300 schools. I’m wondering if it could be faster.

    I think I could improve the time significantly if I use php to iterate through the schools and create 1 SQL query, similar to what was described in this other topic where they recommend:

    INSERT INTO wp_postmea (post_id, meta_key, meta_value) VALUES ("1", "field_1", "value_1"),("1", "_field_1", "field_0123456789"),..... etc.

    update_field() allows me to dump a whole array/object of the “programs” repeater field into a:
    update_field('programs', $data['programs'], $post_id);

    I’m not sure how to handle this into a sql query.

    But my thought is that I could run 1 query to fetch ALL post IDs for every school (instead of a db query inside the foreach to get just 1 postID), and then save that PostID to the school array.

    Then do a foreach for $schools and build a sql query (psuedo code):

    $sql=[]
    foreach($schools as $id => $school) {
      $sql[] = "INSERT INTO wp_postmeta (post_id, meta_key, meta_value) 
      VALUES ($school[post_id], "meta_key for programs(?)", $school['programs'])
      ON DUPLICATE KEY UPDATE meta_value = $school['programs']"
    }
    
    $sql_query = implode(' ; ', $sql);
    
    $wpdb->query($sql_query)

    This would allow PHP to run quickly to build one large sql query, with just 1 wpdb query to insert OR update all schools/programs.

    At this point I’m just curious if I can update an entire repeater field w/ a sql query this way?

  • Helping

    Saving dynamically populated group sub fields

    I have a custom post type “Client”, and a custom taxonomy “Region”. I would like to set a different “logo weight” value for each client’s region, and store it in a region_weights array.
    I created a region_weights ACF field of type “Group”, into which i want to dynamically include the sub fields (1 per region attached to the client).

    
    define('REGION_WEIGHTS_FIELD_KEY', 'field_6668114add626');
    
    add_filter('acf/prepare_field/key=' . REGION_WEIGHTS_FIELD_KEY, 'prepare_region_weights_field');
    
    function prepare_region_weights_field($field)
    {
        global $post;
    
        // Only apply this to the 'region_weights' field group
        if ($field['_name'] !== 'region_weights' || $post->post_type !== 'client') {
            return $field;
        }
    
        // Get the regions associated with this client
        $regions = wp_get_post_terms($post->ID, 'region');
    
        if (is_wp_error($regions) || empty($regions)) {
            return false; // No regions, no fields to display
        }
    
        $field_value = get_post_meta($post->ID, REGION_WEIGHTS_FIELD_KEY, true);
    
        // Generate a field for each region
        foreach ($regions as $region) {
            $field_name = 'field_region_weights_' . $region->term_id;
    
            $default_value = isset($field_value[$field_name]) ? $field_value[$field_name] : 0;
            $region_field = array(
                'key' => $field_name,
                'label' => $region->name . ' Logo Weight',
                'name' => $field_name, // Use the correct field name
                'type' => 'select',
                'instructions' => 'How often should the ' . $region->name . ' logo appear?',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'choices' => array(
                    0 => 'Logo should not appear',
                    1 => 'Logo should appear once in a while',
                    2 => 'Logo should appear pretty often',
                    3 => 'Logo should appear most often',
                ),
                'default_value' => $default_value,
                'value' => $default_value, // Use the correctly formatted meta key for the value
                '_name' => 'region_weights',
                'parent' => $field['key'],
                '_valid' => 1,
            );
            $field['sub_fields'][] = $region_field;
        }
        // Replace the original field with the generated fields
        return $field;
    }
    

    That part works. What does not work is that i cannot save the fields. The update_field function I attached to the ‘acf/save_post’ action hook returns false and I fail to see why. Can you help ?

    
    add_action('save_post', 'save_client_regionWeights');
    
    function save_client_regionWeights($post_id)
    {
    
        // Check if we're saving a 'client' post type
        if (get_post_type($post_id) !== 'client') {
            return;
        }
    
        // Check user permissions
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
    
        // Check if it's an autosave
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
    
        // Check if ACF data is being saved
        if (!isset($_POST['acf'])) {
            return;
        }
    
        if (!isset($_POST['acf'][REGION_WEIGHTS_FIELD_KEY])) {
            return;
        }
    
        // Get the regions associated with this client
        $regions = wp_get_post_terms($post_id, 'region');
        if (is_wp_error($regions) || empty($regions)) {
            // No regions, nothing to save
            return;
        }
    
        // Prepare an array to hold our region weights data
        $region_weights_data = array();
    
        // Loop through each region and collect the weight data from $_POST
        foreach ($regions as $region) {
            $field_name = 'field_region_weights_' . $region->term_id;
            if (isset($_POST['acf'][REGION_WEIGHTS_FIELD_KEY][$field_name])) {
                // Add this region's weight to our data array
                $region_weights_data[$field_name] = $_POST['acf'][REGION_WEIGHTS_FIELD_KEY][$field_name];
            } else {
                // If no weight was set, default to 0
                $region_weights_data[$field_name] = 0;
            }
        }
    
        // Update the region weights data
        update_field(REGION_WEIGHTS_FIELD_KEY, $region_weights_data, $post_id);
    }
    

    If I print the content of $_POST[‘acf’] I get sensible data:

    
    Array
    (
        [field_646f1e398ee52] => Client Something
        [field_63c684c9f2e59] => 95926
        [field_63c93f5d38405] => 95921
        [field_65cde112bc88c] => 2
        [field_6668114add626] => Array
            (
                [field_region_weights_315] => 2
            )
    
    )
    

    What am I doing wrong ?

  • Helping

    Use shortcode in textarea on options page in loop

    I have an option page where you can save an email body text to send out to customers. To make it personal I use shortcodes within the body text like this:

    Dear [yl_first_name],

    How are you today?

    Kind regards,
    Team X

    ————————-

    The email sends out with WordPress cronjob and all works fine except for 1 thing:

    Because ‘officially’ the FIRST NAME is NOT called in the below WordPress loop >> Its the shortcode that is called (via the option page) in the loop…

    I always get the same name value (latest post in line).

    Here’s my EMAIL SEND code:

    // Follow-up e-mail met reviewverzoek
    function yl_follow_up_email_review_function() {

    $review_days_after = get_field(‘booking_settings_review_delay’, ‘booking_settings’);
    $review_url = get_field(‘booking_settings_review_url’, ‘booking_settings’);

    if ($review_days_after && $review_url) {

    $bookings = array(
    ‘posts_per_page’ => -1,
    ‘post_type’ => ‘booking’,
    ‘meta_query’ => array(
    ‘relation’ => ‘AND’,
    array(
    ‘key’ => ‘booking_status’,
    ‘value’ => array(‘confirmed’, ‘changed’),
    ‘compare’ => ‘IN’,
    ),
    array(
    ‘key’ => ‘booking_send_mail’,
    ‘value’ => ‘ja’,
    ‘compare’ => ‘=’,
    ),
    ),
    );

    // De Query
    $query = new WP_Query($bookings);

    // De Loop
    if ($query->have_posts()) {
    while ($query->have_posts()) {
    $query->the_post();

    // Controleer of de poststatus ‘publish’ is
    if (get_post_status() == ‘publish’) {

    // Verkrijg aangepaste velden van de huidige boeking
    $to = get_field(‘booking_email’);

    // Zorg ervoor dat deze velden bestaan in je booking_settings
    $booking_settings_id = ‘booking_settings’; // De ID van de booking settings post

    $sender_name = get_field(‘booking_email_from_name’, $booking_settings_id);
    $sender_email = get_field(‘booking_email_from_email_address’, $booking_settings_id);
    $subject = get_field(‘booking_email_subject_review’, $booking_settings_id);
    $message = get_field(‘booking_email_message_review’, $booking_settings_id); // the above body text with the shortcode inside

    $headers = array(
    ‘From: ‘ . $sender_name . ‘ <‘ . $sender_email . ‘>’,
    ‘Content-Type: text/html; charset=UTF-8’
    );

    // Verzend de e-mail en log eventuele fouten
    if (wp_mail($to, $subject, $message, $headers)) {
    error_log(“Email successfully sent to $to for booking ID: ” . get_the_ID());
    } else {
    error_log(“Failed to send email to $to for booking ID: ” . get_the_ID());
    }

    // Update met nieuwe waarde
    update_field(‘booking_status’, ‘completed’);

    // Pauzeer 10 seconden voordat de volgende e-mail wordt verzonden
    sleep(10);
    }

    // Reset de postdata
    wp_reset_postdata();
    }
    }
    }
    }
    add_action(‘yl_follow_up_email_review’, ‘yl_follow_up_email_review_function’);

    The Shortcode code:

    // Get ACF ‘First name’ values via shortcode
    function yl_booking_first_name_shortcode() {
    global $post; // Haal de globale $post variabele op
    return get_field(‘booking_first_name’, $post->ID);
    }
    add_shortcode(‘yl_booking_first_name’,’yl_booking_first_name_shortcode’);

    —————-

    So how can I change the code so the correct name in each email is showing?

  • Unread

    Update multiple values in relationship field not possible

    Hello,
    I am using Advanced Custom Fields PRO Version 6.2.7

    Recently I have noticed that when I want to update a relationship field with multiple values, the whole ARRAY is not saved, but only the first value of the ARRAY.

    I have used this code as a test:
    update_field('menu', array(123,456), $post_id);

    This is the output with var_dump:
    int(123)

    These are my settings for the relationship field:
    {
    "key": "field_60c789afded44",
    "label": "menu",
    "name": "menu",
    "aria-label": "",
    "type": "relationship",
    "instructions": "",
    "required": 1,
    "conditional_logic": 0,
    "wrapper": {
    "width": "",
    "class": "",
    "id": ""
    },
    "wpml_cf_preferences": 1,
    "post_type": [
    "product"
    ],
    "taxonomy": [
    "product_cat:new"
    ],
    "filters": [
    "search",
    "taxonomy"
    ],
    "elements": "",
    "min": "",
    "max": "",
    "return_format": "id",
    "bidirectional_target": []
    },

  • Solving

    Total Number of Checkboxes Checked

    Hi, I thought figured this out but I guess I jumped the gun. I am trying to auto calculate the a number field by the total amount of checkboxes that are checked. I have multiple custom fields that I am doing this with.

    The top one works perfectly but when I add the second one and so on, it gives me an error.
    count(): Argument #1 ($value) must be of type Countable|array

    
    add_action('acf/save_post','calc_titles');
    $post_id = 'teams';
    
    function calc_titles($post_id) {
    	
    //First Part that works
    	$value = count(get_field('16th_region_title_year_won'));
    	$sixteen = "total_16th_region_titles";
    	update_field($sixteen,$value,$post_id);
    
    //Second Part
    	$value = count(get_field('3rd_region_title_year_won'));
    	$third = "total_3rd_region_titles";
    	update_field($third,$value,$post_id);
    }
    

    Thanks!

  • Solved

    Auto send REVIEW REQUEST email via Cron Job

    I have created a code to auto send booking emails after a booking status is updated. Depending on the booking status, a certain e-mail text is called. This function works perfectly so feel free to use it 😉

    
    // Send notification emails to guests
    function yl_send_booking_email_after_status_update($post_id) {
    
        // Get submitted values.
        $values = $_POST['acf'];
    
        // Check if a specific value was updated.
        if ( isset($_POST['acf']['field_5fbcef66c1d3f']) ) {
    
            $send_email     = $_POST['acf']['field_5fbcef66c1dce'];
            $booking_status = $_POST['acf']['field_5fbcef66c1d3f'];
    
            $to = $_POST['acf']['field_5fbcef66c18b8'];
    
            if ( $send_email == 'yes' &&  $booking_status != 'gesloten' ) {
    
                if ( $booking_status == 'bevestigd' ) {
                    $subject = get_field('booking_email_subject_confirmed', 'booking_settings');
                    $message = get_field('booking_email_message_confirmed', 'booking_settings');
                } elseif ( $booking_status == 'gewijzigd' ) {
                    $subject = get_field('booking_email_subject_changed', 'booking_settings');
                    $message = get_field('booking_email_message_changed', 'booking_settings');
                } elseif ( $booking_status == 'geannuleerd' ) {
                    $subject = get_field('booking_email_subject_canceled_by_guest', 'booking_settings');
                    $message = get_field('booking_email_message_canceled_by_guest', 'booking_settings');
                } elseif ( $booking_status == 'door ons geannuleerd' ) {
                    $subject = get_field('booking_email_subject_canceled_by_us', 'booking_settings');
                    $message = get_field('booking_email_message_canceled_by_us', 'booking_settings');
                }
    
                $headers = array
                (
                    'From: ' . get_bloginfo('name') . ' <' . get_bloginfo('admin_email') . '>',
                    'X-Mailer: PHP/' . phpversion(),
                    'MIME-Version: 1.0',
                    'Content-type: text/html; charset=iso-8859-1'
                );
                $headers = implode( "\r\n" , $headers );
    
                wp_mail( $to, $subject, $message, $headers );
    
            }
    
        }
    
    }
    
    add_action('acf/save_post', 'yl_send_booking_email_after_status_update', 5);
    

    Now I want to chanllange myself a bit further. I want to auto send (via cron job) a ‘Review request’ email ‘X hours’ after the booking date/time. But I’m stuck for a while now.

    Emails do get send but only with pre text. The actuall content of the booking (name, date, time, etc) is left blank.

    When I use $post_id in the function, no emails are being send. I hope I made myself a bit clear.

    Here’s what I have:

    
    // Send review emails to guests
    function yl_send_review_email_function($post_id) {
    
        // Get submitted values.
        $values = $_POST['acf'];
    
        $send_email     = $_POST['acf']['field_5fbcef66c1dce'];
        $booking_status = $_POST['acf']['field_5fbcef66c1d3f'];
        $review_delay   = get_field('booking_settings_review_delay', 'booking_settings');
    
        $to             = '[email protected]';
    
        $subject = get_field('booking_email_subject_review', 'booking_settings');
        $message = get_field('booking_email_message_review', 'booking_settings') . '<br /><br />' . $send_email . '<br /><br />' . $booking_status . ' dit no ' . $review_delay;
    
        $headers = array
            (
            'From: ' . get_bloginfo('name') . ' <' . get_bloginfo('admin_email') . '>',
            'X-Mailer: PHP/' . phpversion(),
            'MIME-Version: 1.0',
            'Content-type: text/html; charset=iso-8859-1'
        );
        $headers = implode( "\r\n" , $headers );
    
        wp_mail( $to, $subject, $message, $headers );
    
        $status = 'gesloten';
        update_field( 'booking_status', $status );
    
    }
    
    add_action('acf/save_post', 'yl_send_review_email_function', 5);
    
    // Time schedule for Cron Job Event
    function yl_cron_schedules($schedules){
        if(!isset($schedules["1min"])){
            $schedules["1min"] = array(
                'interval' => 1*60,
                'display' => __('Once every minute')
            );
        }
        if(!isset($schedules["5min"])){
            $schedules["5min"] = array(
                'interval' => 5*60,
                'display' => __('Once every 5 minutes')
            );
        }
        if(!isset($schedules["30min"])){
            $schedules["30min"] = array(
                'interval' => 30*60,
                'display' => __('Once every 30 minutes')
            );
        }
        return $schedules;
    }
    
    // Schedule Cron Job Event
      if (!wp_next_scheduled('yl_booking_review_mailer')) {
          //You can now use '5min', '20min' or any of the default here
          wp_schedule_event( time(), '1min', 'yl_booking_review_mailer' );
      }
    
      add_action( 'yl_booking_review_mailer', 'yl_send_review_email_function' ); 
    

    PS. I left the needed IF STATEMENTS out to be sure that’s nog stopping emails going out.

  • Solved

    Calculated ACF fields conflict with acf/format_value

    Hello,

    I have a group of ACF number fields on an Options page for basic automatic calculations. All field values (entered and calculated) are then output to pages/posts using ACF shortcodes. Everything works great…until I add an acf/format_value function to format all numbers with commas. My understanding is that ACF/format_value only runs on the front end of the website. However, once my function is enabled, my calculated fields on the Options page are incorrect. I have a feeling I am missing something very basic – any suggestions are greatly appreciated.

    Below is an example of the code I am using.

    
    add_action('acf/save_post', 'count_my_pets', 5);
    
    function count_my_pets($post_id)
    {
    	$post_id = "options";
    
    	// ACF Option page field values.
    	$dogs = get_field('my_dogs', 'options');
    	$cats = get_field('my_cats', 'options');
    	$birds = get_field('my_birds', 'options');
    
    	// Calculate total pets.
    	$pets_total = $dogs + $cats + $birds;
    
    	// Update ACF field for total_pets.
    	update_field('total_pets', $pets_total, $post_id);
    }
    
    add_filter('acf/format_value/type=number', 'format_numbers', 10, 3);
    
    function format_numbers($value, $post_id, $field)
    {
    	$value = number_format($value);
    	
    	return $value;
    }
    
  • Unread

    Programatically updating repeater fields not working as should

    I have an ACF repeater field to collect a list of items.

    According to this topic, and the official update field documentation, I have followed the structure indicated.

    My code looks like this

    $repeater_key = 'field_630a7a6160224';
    $value = array(
    array( 'field_630a7a7d60225' => $value )
    );
    update_field( $repeater_key, $value, $recipe_id );

    This seems to work fine and I can see the info as an array in the post custom field data as shown here – https://prnt.sc/4eYgDvHkdF7i

    However, the repeater itself does not update with the info – https://prnt.sc/oR6Oe3KE1ngb

    How do I get this to update the repeater field correctly please? Not sure what part of this is wrong since the info is being saved to the custom field metadata.

  • Solved

    Field value update using update_field doesn’t show on backend…

    I’ve given up on a support ticket. I sincerely hope you good people can help with this.

    I’ve written a custom plugin that among other things creates a new post type, then registers acf fields to that post type. Everything with this plugin seems to work as expected.

    However, I’m now trying to use a simple script in an mu-plugin to get values from old fields made with a different custom field plugin, and save those values to the newly registered ACF fields. After the hooks ran, there was no update showing on the backend, ie the values of the acf fields were still blank.

    I’m sure I’m missing something simple.

    This…

    
    function update_owner_name_value_update_field($post_id) {
    
        $old_owner_name = old_field_name;
    
        // verified: $old_owner_name returns string "DAVE"
    
        if( have_rows('field_q3md98zvnm241', $post_id) ) :
    
            while( have_rows('field_q3md98zvnm241', $post_id) ) : the_row();
            
                update_sub_field('field_4v8yw6n2hbpqs', $old_owner_name, $post_id);
    
            endwhile;
    
         endif;
    
    }
    
    add_filter('acf/save_post', 'update_owner_name_value_update_field', 10, 1);
    

    …seems to be adding the value, but perhaps in a newly created field rather than the registered field.

    I could be wrong about that, but in the DB postmeta…
    meta_key:
    additional_information_0_owner_name
    value:
    string “DAVE”
    …NOTE the 0 in this meta_key

    This value does NOT appear for field_4v8yw6n2hbpqs (owner_name) on the backend post editor screen for the given $post_id following a save of that post. It can be accessed and returned using get_field with the same field key though.

    On the other hand, This…

    
    function update_owner_name_value( $value, $post_id, $field, $original ) {
    
        $old_owner_name = old_field_name;
    
        // verified: $old_owner_name returns string "DAVE"
    
        if( is_string($value) ) {
    
            $value = $old_owner_name;
    
        }
    
        return $value;
    
    }
    
    add_filter('acf/update_value/key=field_4v8yw6n2hbpqs', 'update_owner_name_value', 10, 4);
    

    …absolutely works!

    in the DB postmeta…
    meta_key:
    additional_information_owner_name
    value:
    string “DAVE”
    … no zero in this meta_key.

    The value for this DOES appear in field_4v8yw6n2hbpqs (owner_name) on the backend post editor screen for the given $post_id following a save of the post.

    I need to be able to use the first method (update_field function) to achieve the same basic result as the second method (acf/update_value hook), wherein the the value actually shows up on the post editor screen.

    Here’s my field registration function (reduced to focus on the owner_name field)…

    
    function register_custom_fields() {
    
        if (function_exists('acf_add_local_field_group')) {
        
            acf_add_local_field_group(
                
                array(
    
                    'key' => 'group_5fd8be3a8aef1',
                    'title' => 'Dealer Fields',
                    'fields' => array(
                    
                        array(
    
                            'key' => 'field_q3md98zvnm241',
                            'label' => 'Additional Information',
                            'name' => 'additional_information',
                            'type' => 'group',
                            'sub_fields' => array(
                            
                                array(
    
                                    'key' => 'field_4v8yw6n2hbpqs',
                                    'label' => 'Owner Name',
                                    'name' => 'owner_name',
                                    'type' => 'text',
    
                                ),
                                
                            ),
    
                        )
                        
                    )
                    
                )
    
            );
    
        }    
    
    }
    

    This registration function runs on init, whereas the others are in an mu-plugin, and run on the hooks shown at priority 10. If this needs to be changed please advise.

  • Helping

    Saving Custom Field Group Meta

    Hi all.

    I’m trying to save some custom field group meta to my acf field group. I want to use this meta to further expand some logic for my wordpress theme.

    I am able to get the meta field to show, But no matter what i do i do not seem to be able to save the value to my field group, Hopefully someone can point me in the correct direction.

    add_filter(
        'acf/field_group/additional_group_settings_tabs',
        function ( $tabs ) {
            $tabs['additional_settings'] = "Additional Settings";
            return $tabs;
        }
    );
    add_filter('acf/field_group/render_group_settings_tab/additional_settings', 'add_additional_settings_fields');
    
    function add_additional_settings_fields($field_group) {
        acf_render_field_wrap(array(
            'label' => 'Is Component', 
            'type' => 'true_false',
            'name' => 'is_component',
            'value' => isset($field_group['is_component']) ? $field_group['is_component'] : 0,
            'instructions' => 'Check this box if this Field Group belongs to a component.', 
            'ui' => 1, // 
        ), 'div', 'acf-field-component-flag');
    
        return $field_group;
    }
    
    add_filter('acf/update_field_group', 'save_additional_settings_field_group_settings', 10, 1);
    
    function save_additional_settings_field_group_settings($field_group) {
        if (isset($_POST['is_component'])) {
            $field_group['is_component'] = $_POST['is_component'];
        }
        return $field_group;
    }
  • Solving

    Repeater to manage a custom post type

    Hello
    I use a repeater in a “master” post (cpt) to manage (create, update, delete) a child post (cpt).

    If a new entry is created in the repeater and the master is saved, I use “acf/save_post” to loop over the rows and create the child(s). Then I update the field “kurs_id” in the repeater of the master with ID of the created child:


    $id = Id of the new created child post.
    $loop_nr = the number of the repeater row.
    $this->parent_post_id = "master" id (post with the repeater).

    private function ckc_update_parent_post( $id, $loop_nr ) {
    $kurse_repeater = get_field( 'kurse_repeater', $this->parent_post_id );
    for ( $i = 0; $i < count( $kurse_repeater ); $i++ ) {
    if ( $i === $loop_nr ) {
    $kurse_repeater[ $i ]['kurs_id'] = $id;
    }
    }
    update_field( 'kurse_repeater', $kurse_repeater, $this->parent_post_id );
    acf_flush_value_cache( $this->parent_post_id, 'kurse_repeater' );
    }

    Creating and updating works. But when deleting I have a problem with the field kurs_id in the repeater.

    If I delete a child in the repeater, e.g. row 3 of 4, all content of row 4 moves to row 3 but not the value of the kurs_id field.
    For example, row 3 has the kurs_id 33 and row 4 has the kurs_id 44. If I delete row 3 and row 4 becomes row 3, the kurs_id field still shows the value 33 (all other fields have the content of the original row 4).

    Am I making a mistake when I update the kurs_id field or why is only the value of the course_id field not transferred?

    I am grateful for any idea that helps me to fix this problem. Thank you for your help!

  • Solving

    update_field() doesn’t store value in repeater field

    I have a repeater that has a read-only field that has a shortcode with an unique id. I need this ID, so I can have shortcodes that can output the other values in the repeater row.

    This is the (summarized) way I add fields:

    
    acf_add_local_field_group(
        'key' => 'pricing_group',
        'title' => 'Pricing',
        'fields' => [
            'key' => 'pricing_user_monthly_fees',
            'label' => 'User Monthly Fees',
            'name' => 'user_monthly_fees',
            'type' => 'repeater',
            'instructions' => 'Please create different fee ranges depending on the amount of users the customer wants to sign-up for.',
            'layout' => 'table',
            'button_label' => 'Add Range',
            'sub_fields' => [
                [
                    'key' => 'pricing_user_monthly_fees_minimum',
                    'label' => 'Minimum',
                    'name' => 'minimum',
                    'type' => 'number',
                    'instructions' => 'Please enter a minimum value for this range.',
                    'wrapper' => [ 'width' => '20' ],
                    'min' => 0,
                    'parent_repeater' => 'pricing_user_monthly_fees',
                ],
                [
                    'key' => 'pricing_user_monthly_fees_maximum',
                    'label' => 'Maximum',
                    'name' => 'maximum',
                    'type' => 'number',
                    'instructions' => 'Please enter a maximum value for this range.',
                    'wrapper' => [ 'width' => '20' ],
                    'min' => 0,
                    'parent_repeater' => 'pricing_user_monthly_fees',
                ],
                [
                    'key' => 'pricing_user_monthly_fees_fee',
                    'label' => 'Fee',
                    'name' => 'fee',
                    'type' => 'number',
                    'instructions' => 'Please enter a fee for this range.',
                    'wrapper' => [ 'width' => '20' ],
                    'parent_repeater' => 'pricing_user_monthly_fees',
                ],
                [
                    'key' => 'pricing_user_shortcode',
                    'label' => 'Shortcode',
                    'name' => 'shortcode',
                    'type' => 'text',
                    'readonly' => 1,
                    'instructions' => 'When you save this range, a shortcode is generated as a read-only field. You can use this shortcode to display the range\'s fee.',
                    'wrapper' => [ 'width' => '40' ],
                    'parent_repeater' => 'pricing_user_monthly_fees',
                ],
            ],
        ],
        'location' => [
            [
                [
                    'param' => 'options_page',
                    'operator' => '==',
                    'value' => 'acf-options-pricing',
                ],
            ],
        ],
    );
    

    This is the function that generates a shortcode with an unique id:

        
    public function store_unique_shortcode(string $post_id)
        {
            $screen = get_current_screen();
    
            if ($post_id !== 'options'
                && !isset($screen->id)
                && !strpos($screen->id, 'acf-options-pricing')) { return; }
    
            $field = get_field('pricing_user_monthly_fees', $post_id);
    
            if (!$field) { return; }
    
            $user_monthly_fees = array_map(function($user_monthly_fee) {
                return array_merge($user_monthly_fee, [
                    'shortcode' => $user_monthly_fee['shortcode'] ?:
                        sprintf('[pricing_user_monthly_fee id="%s"]', uniqid()),
                    ]);
            }, $field);
    
            update_field('pricing_user_monthly_fees', $user_monthly_fees, $post_id);
        }
    

    The problem is that when I use get_field() it shows an empty shortcode value while I expect it to contain the shortcode string with a unique id.

    If I dump $field I get the following:

    
    array(1) {
      [0]=>
      array(4) {
        ["minimum"]=>
        string(1) "0"
        ["maximum"]=>
        string(1) "3"
        ["fee"]=>
        string(4) "18.5"
        ["shortcode"]=>
        string(0) ""
      }
    }
    

    If I dump $user_monthly_fees I get the array with the shortcode and the generated unique id.

    
    array(1) {
      [0]=>
      array(4) {
        ["minimum"]=>
        string(1) "0"
        ["maximum"]=>
        string(1) "3"
        ["fee"]=>
        string(4) "18.5"
        ["shortcode"]=>
        string(50) "[pricing_user_monthly_fee id="646c94d8b29f2"]"
      }
    }
    

    If I dump right after update_field() I get an array with an empty shortcode value.

    
    array(1) {
      [0]=>
      array(4) {
        ["minimum"]=>
        string(1) "0"
        ["maximum"]=>
        string(1) "3"
        ["fee"]=>
        string(4) "18.5"
        ["shortcode"]=>
        string(0) ""
      }
    }
    

    Why doesn’t get_field() return the shortcode with the generated unique id?

  • Solved

    Update ACF fields in WordPress admin using Ajax

    I have a problem that I’ve been trying to solve for some time now. It seems to me that the task is relevant for those who use ACF and want to substitute fields from one post to another. Somebody may be interested in helping solve this problem, or solved it before.

    There are ACF fields that need to be updated programmatically – substitute fields from another record without reloading the page, i.e. using ajax in the admin.

    What is done:
    1.Connect ajax to admin – functions.php

    add_action( 'admin_enqueue_scripts', function() {
        wp_enqueue_script( 'ajax-acf', get_stylesheet_directory_uri() . '/ajax-acf.js', array( 'jquery' ), time(), true );
    } );

    2.Run jquery when input button is clicked (receive “ok” response) – i use button from ACF Extended plugin.

    jQuery( function ( $ ) {
      $ ('.acf-field-64647e4980e03').click( function(){
        var input = $(this);
        $.ajax({
          type : 'POST',
          url : ajaxurl,
          data:{
            action:'my_acf_update',
            post_id: $_POST['post_id']
         },
          success : function( data ) {
           alert( data );
          }
        })
      } ); 
    } );

    The following hook does not work – only “ok0” is returned in the popup

    add_action( 'wp_ajax_my_acf_update', function(){
      // Get post id
      $post_id = $_POST['post_id'];
      // Get id another post from the relation field
      $another_post_id = get_field('Blocks-FirstSlide-copyBlock', $post_id );
      // Getting data
      $source_fields = get_fields($another_post_id ); 
      // Update fields in this post
      foreach ($source_fields as $field_name => $field_value) {
      update_field($field_name, $field_value, $post_id);
      }
      update_field( 'Blocks-FirstSlide-copyBlock', $another_post_id, $post_id );
      echo 'ok';
      wp_die;
    });

    Also a have hook that solves the problem but with a reboot (when i saving the post). In this case, the true/false field is also manages hook:

    // Substitution of field values
    add_action('acf/save_post', 'my_acf_save_post', 20);
    function my_acf_save_post( $post_id ) {
      // Checking if substitution is needed
      $acf_value = get_field('Blocks-FirstSlide-update', $post_id);
       if ($acf_value == true) {
       // Get id another post from the relation field
       $another_post_id = get_field('Blocks-FirstSlide-copyBlock', $post_id );
       // Getting data
       $source_fields = get_fields($another_post_id ); 
       // Update fields in this post
       foreach ($source_fields as $field_name => $field_value) {
       update_field($field_name, $field_value, $post_id);
       }
       update_field( 'Blocks-FirstSlide-copyBlock', $another_post_id, $post_id );
       }
  • Unread

    save_post to update field if other field has changed

    I thought I got it all sorted, but it just doesn’t work the way I think it should.
    Upon saving a post, I want to check if the value of a field (‘zip’) has been changed (compared to the stored value), and then change the value of another field (‘status’) accordingly. This would be my function:

    function my_acf_save_post( $post_id ) {
    
    	// Get previous value
        $zip_old = get_field('zip', $post_id);
    
    	// Get value from input
    	$zip_new = $_POST['acf']['field_6463644299953'];
    
        if($zip_old != $zip_new) {
            $status = 'changed';
        } else {
    		$status = 'unchanged';
    	}
    
    	// Update field with $status message
    	update_field('status', $status, $post_id);
    }
    
    add_action('acf/save_post', 'my_acf_save_post', 5);

    From my understanding, this should detect if the value for the ‘zip’ field is different from the stored one and change the ‘status’ value. But even when I changed the ‘zip’ field value and saved the post, the ‘status’ still remains ‘unchanged’. Is there something in my logic that doesn’t make sense?

  • Helping

    Read content of uploaded PDF file and save it ACF field

    I have a custom post type “movies” with ACF file upload field called “document_file”. I would like to save the content of the uploaded PDF document to another ACF textarea field called “document_content”. I have a working PHP code using XPDF binaries and a PHP library, that reads PDF content and returns a string with this content.

    I’m using following code to update ACF field:

    function set_field_value( $post_id ) {
        global $post;
        $post_id = $post->ID;
        $posttype = get_post_type($post_id);
        $value = 'some sample text'; // this should be a string which we get from uploaded pdf documentcontent 
    
        $document_content = get_field('document_content', $post_id);
    
        if ($posttype == 'movies' & empty($document_content)) {
            update_field('document_content', $value, $post_id);
        }
    }
    add_action('acf/save_post', 'set_field_value');

    This works, but I would like to pass a $value variable from a function attached to file upload hook to a function set_field_value() in acf/save_post hook, but I’m not sure how to do it – which hook to use on ACF file upload. Example function, which reads PDF content:

    function read_pdf_content( $post_id ) {
        require __DIR__ . '/vendor/autoload.php';
        $logger = null;
    
        $document_file = get_field('document_file', $post_id);
    
        if( $document_file ) {
        
            $pdfToText = XPDF\PdfToText::create(array(
                    'pdftotext.binaries' => '../../../../usr/bin/xpdf/bin64/pdftotext'
                ), $logger);
    
            $document_content_txt = $pdfToText->getText($document_file['filename']);
            // remove non-latin characters
            $pdf_content = preg_replace('/[^\00-\255]+/u', '', $document_content_txt);
    
            //update_field('document_content', $pdf_content, $post_id);
        } else {
            $pdf_content = '';
        }
    
        return $pdf_content;
    }

    So in this case I would like to pass $pdf_content variable to acf/save_post’ hook, so I could save it in ACF field called ‘document_content’.

    Is wp_handle_upload hook a way to go?

    Regards.

  • Solved

    Ninja Forms and ACF Date/Time Picker Not Behaving

    I’ve got a Ninja Form with a Date/Time Picker. I am using update_field to save the value in the database, but it will not work correctly and instead saves the value as:

    a:4:{s:4:"date";s:10:"2023-03-07";s:4:"hour";s:2:"04";s:6:"minute";s:2:"30";s:4:"ampm";s:2:"pm";}

    This breaks the database record since this is not a properly formatted Date/Time – which should be converted to YYYY-MM-DD HH:II:SS in the database by update_field

    What’s weird to me, is that if it’s a Date picker only, the update_field function works just fine. So it appears the issue is with the Time part.

    It’s infuriating.

  • Helping

    How to save acf taxonomy data in other post

    Hi,

    i have an option page with a repeater. In this repeater i have a field taxonomy type with multiple choises.

    I need to get values and save in a same field type but on a custom post type.

    It works for all other fields but not for this type.

    When i enter in the custom post type, i see the correct taxonomy, but it’s not correct infact using wp_query, value is ignored. If i delete that taxonomy and choose it again inside the custom post type, then wp_query works.

    When i create custom post type by code and use update_field(“match_valevole_per_titolo”,$match_valevole_per_titolo,$id_post_creato); i obtain in the db this : a:1:{i:0;i:26;}

    When i delete the taxonomy from custom post type and choose it again from backend, i obtain in the db : a:1:{i:0;s:2:”26″;}

    what i’m doing wrong?

  • Solved

    ACF + Gravity Forms User Registration

    I’m using Gravity Forms User Registration Add-On to register users and assign them a case worker. In ACF Pro I have created a case_worker field (field_636957e952b06) with the Field Type set as User and the Return Format set to User Array. In my registration form I have a drop down field that I’m using Populate Anything to generate the list all of users with the case worker role, with the value set to User ID and the Label set to Display Name. In the User Registration Feed User Meta section the case_worker Key is assigned to the Case Worker field value. When the form is submitted and the user is registered, the backend has the correct case worker displayed on the user profile and the database case_worker meta_key has the correct user ID for the case worker set, but on the frontend the fields will not display with get_field unless I manually save the user profile in the admin. I know I need to save the value to the ACF field after the form is submitted, but so far I have been unsuccessful. This is my most current attempt, there have been many pieced together by scouring both ACF and gravity forms posts, I figured it was time to ask for some help…

    add_action( 'gform_after_submission_4', 'after_submission', 10, 2 );
    function save_additional_user_meta( $user_id ) {
    
    	$user = wp_insert_user( $userdata );
    	update_field('field_636957e952b06', $case_worker, 'user_'.$user);
    
    }
  • Solved

    calculation not updating

    So, i have something like this:

    function perf_pln2($post_id)
    {
    $total = (get_field('zip')+get_field('kraken'))/(get_field('_price')+0.01);
    $value = $total;
    $field_name = "perf";
    update_field($field_name,$value,$post_id);
    }
    add_action('save_post','perf_pln2');
    

    And i have a plugin that synchronize prices, it does update the price, but it doesnt update the calculations based on the price from the code above.
    Its working only when i click the “update” button on each product page, bulk edit doesnt work.
    Im a total noob, i have no idea how to code PHP etc, so please dont bash me :P.
    But how do i fix this, i started reading about acf/save_post, update_field and _value does look like something completely different.
    Still i have no idea, so i just started trying some functions from the internet.

    function _acf_do_save_post ($post_id) {
    	
    	// Check and update $_POST data.
    	if( $_POST['acf'] ) {
    		acf_update_values( $_POST['acf'], $post_id );
    	}	
    }
    
    // Run during generic action.
    add_action( 'acf/save_post', '_acf_do_save_post' );
    

    But no luck so far, please be so kind and help/point me in the right direction.

  • Solving

    Why doesn't this work on acf/save_post when attaching gallery ids?

    		function on_post_save( $post_id, $post, $update) {
    
    			// Get previous values.
    			//$prev_values = get_fields( $post_id );
    		
    			// Get submitted values.
    			//$values = $_POST['acf'];
    
    	    $post_content = html_entity_decode($post->post_content);
                // post_content contains my content with 2 links:
                // <a href='#' data-id='59'>Gallery pop 1 id: 59</a>
                // <a href='#' data-id='55'>Gallery pop 2 id: 55</a>
    
                $dom = new DomDocument();
                @$dom->loadHTML($post_content);
                
                $attachment_ids = array();
                foreach ($dom->getElementsByTagName('a') as $item) {
                   $attachment_ids[] = $item->getAttribute('data-id');
                }
        
                //var_dump($attachment_ids);
    			// die();
      
                if($attachment_ids){
                    ///field key for my ACF Gallery field
                    update_field('field_63a6bd5d2a3d2',$attachment_ids, $post_id);
                }else{
                    update_field('field_63a6bd5d2a3d2',$attachment_ids,$post_id);
                }
    	
    		}
    		add_action('save_post', 'on_post_save',1,5);
  • Unread

    get year value from date field to set the category

    hi
    I have a date filed ( the_date ) in a repeater field , also have a custom taxonomy field ( select with multi choice ) with id the_year .

    I need to grap the years only from the date field and set them as a choosen values in the category field of the post .

    as an example when I set 2 values in the date field of ( 22.10.2020 and 21.10.2022 ) the term field must check the 2020 and 2022 categories after saving or updating the post.

    whould you please help with the function to use.

    I tried this function but not working.

    function UpdateYearField($post_id){
    $year_field = get_field('the_year',$post_id);
    $full_date = get_field('the_date',$post_id);
    $year_from_date = DateTime::createFromFormat('Ymd', $full_date)->format('Y'); // will get the year from the $full_date
    
    update_field('the_year', $year_from_date ,$post_id);
    }
    add_action('acf/save_post', 'UpdateYearField', 20);
Viewing 25 results - 1 through 25 (of 381 total)