Mass Update lines of code for all posts

This script will get all posts and replace it content according to your needs:

function wpse_287574_replace_content() {

    // Get all posts
    $query = new WP_Query(array(
        'post_type' => 'post',
        'posts_per_page' => -1,
    ));

    $posts = $query->get_posts();

    foreach ($posts as $post) {

        // Get content
        $content = $post->post_content;

        // Regex and replacement
        $regex = '/^(\<a\s+data-name=\".+\")(\>(.+)\<\/a\>)$/';
        $replacement="$1 href="https://wordpress.stackexchange.com/items/?item="$2";

        // Replace content
        $new_content = preg_replace($regex, $replacement, $content);


        // Prepare arguments
        $args = array(
            'ID' => $post->ID,
            'post_content' => $new_content,
        );

        // Update post
        wp_update_post( $args );
    }
}

add_action('init', 'wpse_287574_replace_content');

Leave a Comment