0

I am attempting to take some custom field meta data (generated via the ACF plugin) and save it as post meta with a function. This is what I've come up with:

function tps_create_slotcode($post_id) {
    if (get_post_type($post_id) == 'space-rental') {
        $slotCodes = array();
        while (have_rows('dates_and_times', $post_id)) {
            the_row();
            $date = get_sub_field('date');
                $dateStamp = strtotime($date);
            $start = get_sub_field('start_time');
            $end = get_sub_field('end_time');
            $space = get_sub_field('space'); //term id
                $spaceTerm = get_term($space, 'spaces');

            $slotCodes[] = $spaceTerm->slug.'_'.$start.'_'.$date;
        }
        update_post_meta($post_id, 'slotCodes', $slotCodes);
    }
}
add_action('acf/save_post', 'tps_create_slotcode', 40);

I have tested all variable to make sure they are producting a value, and they are, but the update_post_meta call is not doing anything.

If I put the update_post_meta INSIDE the loop, it works but only saves the last result (obviously) since that's the last iteration of the loop. That would be this code:

    function tps_create_slotcode($post_id) {
        if (get_post_type($post_id) == 'space-rental') {
            while (have_rows('dates_and_times', $post_id)) {
                the_row();
                $date = get_sub_field('date');
                    $dateStamp = strtotime($date);
                $start = get_sub_field('start_time');
                $end = get_sub_field('end_time');
                $space = get_sub_field('space'); //term id
                    $spaceTerm = get_term($space, 'spaces');

                $slotCodes = $spaceTerm->slug.'_'.$start.'_'.$date;
update_post_meta($post_id, 'slotCodes', $slotCodes);
            }
            update_post_meta($post_id, 'slotCodes', $slotCodes);
        }
    }
    add_action('acf/save_post', 'tps_create_slotcode', 40);

Can anyone tell me what I'm doing wrong in the first example? Will update_post_meta not save an array of data or something?

0

Figured it out. I had to re-read the codex a lot to figure out that when you pass an array to update_post_meta it is serialized. By using maybe_unserialize() on the return value I was able to to get access to the values. Hope this helps some future searcher!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.