I'd like to do a search and replace of post titles but only affect those with a specific tag.


Change post title: This is a new post

to: This is an old post

but on only on posts that have the tag: old

  • 1
    Please show us what have you tried. – Nilambar Apr 20 '15 at 9:59
  • I looked at some search and replace plugins but couldn't find one where the option was just to change posts with a specific tag. – Austin Apr 20 '15 at 13:25
//Search by tags
$query = new WP_Query( 'tag=old' );

// Then update post titles 
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        //check if title have "a new"
        if(strpos(get_the_title(),'a new') !== false) :

            $post = array(
                'ID'=> get_the_id(),
                'post_title'=> str_replace('a new','an old',get_the_title())

            // Update the post into the database
            wp_update_post( $post );

  • Wouldn't this update all posts with tag=old to the new post title? I only want to update those that have matching title 'This is a new post'. More specifically I only want to change that part of the title. Search and replace 'a new' to 'an old'. – Austin Apr 20 '15 at 11:23
  • @Austin i have updated code according to your requirements – M Haseeb Apr 20 '15 at 11:59
  • @M Thanks for the updated code. I'm assuming this will change the whole title to "This is an old post"? I only want to change the part 'a new' and replace it with 'an old'. The title I have given is just an example - I have 100's of posts with different titles but common words that I have to replace. – Austin Apr 20 '15 at 13:36
  • @Austin i replaced it again :) – M Haseeb Apr 20 '15 at 17:56

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.