1

I run the following:

Note: usp-custom-8 is a custom field with a string like "United States" or "china" etc

Sometimes the nations have an extra string at the beginning like: "[Image] United States" and I need to remove ["Image"] and leave the country name only. With the following I was trying to check if the custom field has a particular string and if so, change it and update the field. But it isn't working and also, this won't be a general code which in one shot will remove all ["Image"] but I'd have to manually run it for each country.

if (have_posts()) : while (have_posts()) : the_post();
  $title = usp_get_meta(false, 'usp-custom-8');
  if (preg_match('/\b[Image] United States\b/', $title)) {
   update_post_meta( $post->ID, 'usp-custom-8', 'United States' );
  }
endwhile; endif;
rob.m
  • 9,843
  • 19
  • 73
  • 162

1 Answers1

1

You could go for the simplest option of just replacing [Image] with a blank using str_replace()...

if (have_posts()) : 
    while (have_posts()) : 
        the_post();
        $title = usp_get_meta(false, 'usp-custom-8');
        update_post_meta( $post->ID, 'usp-custom-8',
            str_replace('[Image]', '', $title ));
    endwhile; 
endif;
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • Problem is that you could come up with 100's of alternatives, unless you come up with a fixed algorithm - you may end up having to have a translation array. One thing you can do is pass `str_replace()` an array of things you want to replace and what you want to replace it with - https://stackoverflow.com/questions/13715826/str-replace-with-array – Nigel Ren Jun 26 '18 at 12:56