Skip to content

Instantly share code, notes, and snippets.

@JoelLisenby
Last active April 20, 2022 04:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoelLisenby/f79d63d9353d04200aae3007b0d802db to your computer and use it in GitHub Desktop.
Save JoelLisenby/f79d63d9353d04200aae3007b0d802db to your computer and use it in GitHub Desktop.
Find and Replace Title and Content for Specific Post Type in WordPress with WP_Query
<?php
/* Backup site first before using. This adds a menu to wp-admin so you can run the script.
*** Visiting this menu will automatically run the script!! ***
*/
add_menu_page(
'jbl Find Replace',
'jbl Find Replace',
'manage_options',
'jbl-find-replace',
'jbl_find_replace'
);
function jbl_find_replace() {
$replacements = array(
array('Search String 1','Replacement String 1'),
array('Search String 2','Replacement String 2')
);
$wpq = new WP_Query( array(
'post_type' => 'custom_post_type',
'date_query' => array(
'before' => '2022-01-01'
),
'posts_per_page' => -1
) );
while ( $wpq->have_posts() ) {
$wpq->the_post();
$jbl_post = array(
'ID' => get_the_ID(),
'post_title' => get_the_title(),
'post_content' => get_the_content()
);
foreach($replacements as $replacement) {
$jbl_post['post_title'] = str_replace( $replacement[0], $replacement[1], $jbl_post['post_title'] );
$jbl_post['post_content'] = str_replace( $replacement[0], $replacement[1], $jbl_post['post_content'] );
}
$result = wp_update_post( $jbl_post, true );
if ( is_wp_error( $result ) ) {
$error_string = $result->get_error_message();
echo '<div id="message" class="error"><p>' . $error_string . '</p></div>';
}
echo "<br>\n";
var_dump($jbl_post);
echo "<br><br>\n";
}
wp_reset_postdata();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment