0

I have a repeating field that stores text terms in an array, like this:

[0] => 
[1] => NUC Lights
[2] => Smoke Alarm
[3] => Binoculars

You'll note key A has no value, and they're not ordered alphabetically. What I want to do is to take the array above, remove empty values, sort it, and resave it like below:

[0] => Binoculars
[1] => NUC Lights
[2] => Smoke Alarm

Here's my current code:

// Post Types to include
$post_args = array(
    'posts_per_page' => -1,
    'post_type' => array(
        'boat'
    ),
);

// The Query
$post_query = new WP_Query( $post_args );
$posts = $post_query->posts;

foreach($posts as $post) {

    $boat_safety_terms = get_post_meta( $post->ID, 'wpcf-all-safety-terms', false );
    $boat_safety_terms_cleaned = array_filter( $boat_safety_terms );
    $boat_safety_terms_cleaned_sorted = sort( $boat_safety_terms_cleaned );

    error_log( print_r( $boat_safety_terms_cleaned_sorted, TRUE ) );

}

But my log only shows 1 for each boat for some reason. Any idea what might be going wrong with it?

Also, I'm assuming I'll want to use update_post_meta to save the array back to the field?

1
$boat_safety_terms_cleaned_sorted = sort( $boat_safety_terms_cleaned );
error_log( print_r( $boat_safety_terms_cleaned_sorted, TRUE ) );

PHP's sort accepts an array reference and sorts in-place, and returns success or failure - hence the 1 you're getting. You want:

sort( $boat_safety_terms_cleaned );
error_log( print_r( $boat_safety_terms_cleaned, TRUE ) );

Also, I'm assuming I'll want to use update_post_meta to save the array back to the field?

Yes, that would work fine. I assume this is utility method that you'll manually trigger once per post though, and not something that gets run as a matter of course? If it's on save of a boat then there are probably better ways to filter the value as you save it, depending on how you're doing that.

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.