Yoast SEO AI Optimization Bug: Fix & Protect Your SEO

A colleague contacted me recently about a strange discovery in their WordPress blog posts. Using Yoast SEO Premium alongside the Classic Editor, they noticed Yoast was automatically injecting CSS classes that looked like ai-optimize-6, ai-optimize-9, directly into their content.

The issue is that these classes persist within your posts even after you disable Yoast AI Optimize or remove the plugin altogether. This is unexpected, as plugins should ideally leave no trace behind after being uninstalled.

These AI markers may not be visible on your site, but they add unnecessary code to your page source. More importantly, they might indicate to AI content detectors, plagiarism tools, and search engines that your content has been created or optimized using AI.

In this tutorial, I will demonstrate how to remove these hidden classes using a brief code snippet. I will also explain how to apply the code in a secure manner and suggest an alternative SEO plugin that I recommend over Yoast.

Here are the things I will cover in this tutorial:

  • Why These ai-optimize Classes Are Bad for SEO
  • Step 1: Make a Backup Before Making Changes
  • Step 2: Add the Code Snippet to Prevent ai-optimize Classes
  • Step 3: Remove AI Classes From All Posts (Bulk Update)
  • Bonus Tip: Switching to an Alternative SEO Plugin (Better and More Powerful)
  • Bonus SEO Resources

Why These ai-optimize Classes Are Bad for SEO

The ai-optimize-{number}When you utilize Yoast SEO Premium’s AI capabilities alongside the Classic Editor, CSS classes get inserted. While invisible on the front end, these classes are embedded in your content’s HTML source, potentially leading to complications.

To inspect these classes, navigate to any post or page on your site and utilize your browser’s Inspect tool.

Here’s the rationale behind my recommendation to remove them:

  • They introduce clutter into your HTML.These extraneous classes complicate the readability and parsing of your code.
  • They offer no functional benefit.They don’t impact the presentation or functionality of your content; they are simply remnants from the AI tool’s operation.
  • They have the potential to activate AI detection mechanisms.Certain plagiarism detection tools and AI content identifiers are sensitive to these patterns and might erroneously flag your post, even if you are its original author.
  • They distribute traces of AI across your website.If numerous websites employ the identical classes, Google might begin to link that pattern to low-quality AI-generated content or mass-produced material.
  • They heighten the possibility of formatting clashes.Unfamiliar classes could potentially clash with your theme or plugins in the future.

There are no advantages to retaining these concealed markers, but several compelling reasons exist to remove them.

Fortunately, a swift solution exists, and I will guide you through the process safely in the subsequent section.

Step 1: Create a Backup Prior to Implementing Modifications

Prior to proceeding, I strongly advise generating a comprehensive backup of your WordPress site. This process requires minimal time and offers assurance in the event of unforeseen issues.

I use Duplicator when I need a quick and reliable backup solution. It’s the best WordPress backup plugin on the market, it is beginner-friendly, and it works great whether you’re backing up or migrating your site.

  • ✅ WordPress backups, both automatic and on-demand, are available.
  • ✅ Backups are securely kept offsite using services like Google Drive or Dropbox.
  • ✅ Should problems arise, restoring is as easy as a single click.

For details, see our guide on how to back up your WordPress website.

With a current backup prepared, you can proceed to resolve the issue, as I will now demonstrate.

Step 2: Add the Code Snippet to Prevent ai-optimize Classes

Now that you have a backup, you’re ready to remove those ai-optimize-{number} and ai-optimize-introduction classes.

I’ve developed a versatile and secure code snippet compatible with the Block Editor (Gutenberg), the Classic Editor, and bulk editing.

Instead of modifying theme files or using FTP, I advise utilizing the WPCode plugin to implement this snippet. I use it to handle code snippets on WordPress sites, minimizing any risks. (Refer to my comprehensive WPCode review for more information.)

Tip: A free version of WPCode exists, and it’s adequate for this tutorial. However, a paid subscription unlocks the software’s full feature set.

If you haven’t added code to your site previously, review our guide detailing how to add custom code snippets in WordPress without causing site errors.

To begin, make sure the WPCode plugin is installed and active. If needed, refer to our guide on WordPress plugin installation.

With the plugin active, navigate to theCode Snippets » + Add Snippet page and click on ‘+ Add Custom Snippet’ button under the ‘Add Your Custom Code (New Snippet)’ box.

Next, give your code snippet a descriptive title for easy identification.

Then, select PHP Snippet from the ‘Code Type’ options.

Now, copy the following code and paste it into the Code Preview box.

Here’s the full code snippet:

// For Classic Editor and programmatic updates
function strip_ai_optimize_classes($data, $postarr) { if (empty($data['post_content']) || $data['post_type'] !== 'post') { return $data; } $data['post_content'] = strip_ai_optimize_from_content($data['post_content']); return $data;
}
add_filter('wp_insert_post_data', 'strip_ai_optimize_classes', 10, 2);
// For Gutenberg/Block Editor
function strip_ai_optimize_classes_rest_insert($prepared_post, $request) { if (isset($prepared_post->post_content) && $prepared_post->post_type === 'post') { $prepared_post->post_content = strip_ai_optimize_from_content($prepared_post->post_content); } return $prepared_post;
}
add_filter('rest_pre_insert_post', 'strip_ai_optimize_classes_rest_insert', 10, 2);
// For bulk edit operations - this is the key addition
function strip_ai_optimize_classes_bulk_edit($post_id) { $post = get_post($post_id); if (!$post || empty($post->post_content) || $post->post_type !== 'post') { return; } $cleaned_content = strip_ai_optimize_from_content($post->post_content); if ($cleaned_content !== $post->post_content) { remove_action('post_updated', 'strip_ai_optimize_classes_bulk_edit'); wp_update_post(array( 'ID' => $post_id, 'post_content' => $cleaned_content )); add_action('post_updated', 'strip_ai_optimize_classes_bulk_edit'); }
}
add_action('post_updated', 'strip_ai_optimize_classes_bulk_edit');
// Catch bulk operations via the bulk_edit_posts action
function strip_ai_optimize_classes_bulk_action($post_ids) { if (!is_array($post_ids)) { return; } foreach ($post_ids as $post_id) { strip_ai_optimize_classes_bulk_edit($post_id); }
}
add_action('bulk_edit_posts', 'strip_ai_optimize_classes_bulk_action');
// Shared function to strip ai-optimize classes
function strip_ai_optimize_from_content($content) { if (empty($content) || !is_string($content)) { return $content; } return preg_replace_callback( '/classs*=s*["']([^"']*)["']/', function($matches) { $classes = $matches[1]; // Remove ai-optimize-[number] and ai-optimize-introduction $classes = preg_replace('/bai-optimize-(d+|introduction)bs*/', '', $classes); // Clean up spacing $classes = preg_replace('/s+/', ' ', trim($classes)); return empty($classes) ? '' : 'class="' . $classes . '"'; }, $content );
}

After adding the code, scroll down to the ‘Insertion’ section.

Then, select ‘Run Everywhere’ next to the ‘Location’ option.

Finally, go to the top of the page and switch the status toggle in the top-right to Active, and then click on the ‘Save Snippet’ button to store your changes.

Once you’ve added this snippet to your site using WPCode, it will automatically strip these AI-generated classes from any post you create or update in the future.

If you want to remove the ai-classes from existing content, you’ll have to bulk edit your existing content.

🌟Pro Tip: If editing code is outside your comfort zone, don’t worry!

The CanadaCreate team provides Emergency WordPress Support Services that can assist in resolving issues like this swiftly and securely. We are able to clean up your content and configure your SEO plugin correctly.

👉 Get Expert WordPress Support Now

Step 3: Remove AI Classes From All Posts (Bulk Update)

Now that you have the code snippet in place, it will automatically clean up any AI markers when you edit an existing post or publish a new one. But to remove these classes from your older posts, you’ll need to find and replace them in your WordPress database.

To do that, you will need to add another code snippet using WPCode. This one will replace ai-optimize CSS classes from your existing content.

Simply go to the Code Snippets » + Add Snippet page and click on ‘+ Add Custom Snippet’ button under the ‘Add Your Custom Code (New Snippet)’ box.

Next, select ‘PHP Snippet’ using the ‘Code Type’ dropdown. You’ll then need to name the snippet; choose a descriptive title for easy identification.

You’ll then copy the code below into the ‘Code Preview’ area.

/** * Fixes unwanted 'ai-optimize-introduction' and 'ai-optimize-[number]' classes added by Yoast SEO in post content. * Run once and don't forget to disable it */
function wpb_fix_yoast_ai_optimize_classes() { $args = array( 'post_type' => get_post_types(array('public' => true)), // Apply to all public post types 'posts_per_page' => -1, 'post_status' => 'publish', 'fields' => 'ids', // Optimize memory usage ); $query = new WP_Query($args); $fixed_count = 0; if ($query->have_posts()) { global $wpdb; foreach ($query->posts as $post_id) { $content = get_post_field('post_content', $post_id); // Remove both ai-optimize-[number] and ai-optimize-introduction classes $new_content = preg_replace('/bai-optimize-(d+|introduction)b/', '', $content); // Clean up any extra whitespace left behind $new_content = preg_replace('/s+/', ' ', $new_content); if ($new_content !== $content) { $updated = $wpdb->update( $wpdb->posts, array('post_content' => $new_content), array('ID' => $post_id), array('%s'), array('%d') ); if ($updated !== false) { $fixed_count++; error_log("Fixed post ID: $post_id"); } else { error_log("Failed to update post ID: $post_id"); } } } wp_reset_postdata(); } error_log("WPCode cleanup complete. Total posts fixed: $fixed_count"); // Automatically disable this snippet after it runs if (function_exists('wpcode_snippet_deactivate_current')) { wpcode_snippet_deactivate_current(); }
}
// Run only once when the snippet is saved or enabled
add_action('init', 'wpb_fix_yoast_ai_optimize_classes');

Once the code is added, navigate to the ‘Insertion’ area below.

Next, choose ‘Run Everywhere’ found beside the ‘Location’ setting.

Return to the top, set the status to ‘Active’, and then ‘Save Snippet’.

Rest assured, your content remains unchanged. This action scans the database specifically forai-optimizeclasses, and then deletes them.

The snippet is now active. To activate it, simply load any post or page on your website.

This action will remove theai-optimize-{number} and ai-optimize-introductionclasses from all your existing content; no manual changes are required.

After that, use the Inspect tool to ensure no ai-optimize classes are appearing in your content.

Important: After removing theai-optimize classes don’t forget to go back to the Code Snippets page and disable the Removal code snippet.

Note 📝:You should keep the initial code snippet active until either Yoast SEO Premium receives an update or you transition to a different solution.

Bonus Tip: Consider Switching to a Different, More Powerful SEO Plugin

Yoast SEO’s innovation has decreased recently, despite its long-standing presence.

CanadaCreate decided to migrate to All in One SEO on all our platforms several years ago. This significant transition and its detailed reasoning are documented in this study: Why We Switched from Yoast to All in One SEO.

I consistently choose All in One SEO for both my own and my clients’ sites because it provides:

  • ✅ Full AI-driven search functionality including schema markup, advanced sitemaps, and AI integrations.
  • ✅ Streamlined configuration using intelligent defaults and checklists.
  • ✅ Better support for local SEO, WooCommerce, Google News, and more.

If you’re undecided, see our comprehensive comparison: Yoast SEO vs All in One SEO – Which Is the Better Plugin?

Important ⚠️: If you’ve upgraded to Yoast SEO Premium 25.3.1 or later, or have changed to All in One SEO, you can now turn off the code snippet within WPCode.

Simply navigate to theCode Snippetssection in your WordPress dashboard and toggle the snippet to off.

Bonus SEO Resources

Whether you are moving away from Yoast SEO or want to refine your WordPress SEO approach, these resources will help.

These guides and comparisons help streamline your work, prevent errors, and boost SEO results:

  • Best Yoast SEO Alternatives For WordPress
  • The Ultimate WordPress SEO Migration Checklist (For Beginners) – Helps you switch away from Yoast to All in One SEO
  • How to Set Up All in One SEO for WordPress Correctly (Ultimate Guide)
  • Complete WordPress SEO Guide for Beginners (Step by Step)
  • How to Use AI for SEO in WordPress (12 Tools)
  • Is AI Content Bad for WordPress SEO? (Expert Insights & Tips)
  • Beginner’s Guide to Generative Engine Optimization for WordPress

I hope this guide helped you fix the ai-optimize class issue in Yoast SEO and set your site up for better long-term results. You’ve got this—and if you ever need a hand, we’re here to help.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Share This Post
DMCA.com Protection Status Chat on WhatsApp