Migrating Subscriptions from WP Swing to WooCommerce

A Simple and Complete Guide for Store Owners

If your store is using WP Swing Subscriptions and you want to switch to WooCommerce Subscriptions, this guide explains everything in clear and simple English. You will learn how migration works, what steps to follow, what problems you should avoid, and what to check before you go live. This article is written for regular store owners, not developers, but it also includes sample code and advanced tips for those who need them.

The goal is to help you move your subscribers in a safe and clean way without losing revenue or breaking renewal payments.


Why Many Stores Move Away From WP Swing

WP Swing Subscriptions is a cheaper solution, but it has several limits when a store starts to grow. WooCommerce Subscriptions is more stable, has better support, and works with more plugins and gateways.

Below are the most common reasons store owners decide to migrate.

Main reasons to switch

  • More stable renewals
  • Better support and updates
  • Works better with Stripe and PayPal
  • Easier to customize
  • Fewer errors with scheduled payments
  • Better integration with memberships and LMS plugins

Most of the problems store owners report with WP Swing Subscriptions are related to failed renewals, wrong next payment dates, and customer complaints. When money is involved, you want a stable and safe system.


How Migration Works

Migrating subscriptions is not the same as moving normal products. Subscriptions have start dates, renewal dates, unpaid orders, payment tokens, and links to customers. Because of this, the migration process needs to be very careful.

Here is the basic outline of how migration is done.

  1. Export all subscription data from WP Swing
  2. Clean and correct the data
  3. Map the fields to WooCommerce Subscriptions
  4. Import the data using a special importer or a custom script
  5. Test renewals
  6. Disable WP Swing and activate WooCommerce Subscriptions
  7. Watch renewals for a few days

Now we go deeper into each step.


Step 1: Export Data From WP Swing

WP Swing allows subscription export to CSV. You will need these fields:

Field nameWhy it is needed
user IDTo match the subscription with the customer
product IDTo know what product the customer is subscribed to
start dateNeeded for correct billing history
next payment dateNeeded so WooCommerce can create the next renewal
billing cycleMonth, week, year
subscription statusActive, canceled, paused
order IDsUseful for history but not always required
payment methodNeeded for renewals

Make sure to check that all exported rows have valid dates and correct user IDs.


Step 2: Clean the Exported File

Most stores need some cleanup before importing the data into WooCommerce Subscriptions. Common issues include:

  • Invalid dates
  • Missing user accounts
  • Old or deleted product IDs
  • Wrong status values
  • Incomplete payment method information

You can fix most of these issues using Google Sheets or Excel.
For example, if some start dates are empty, you can set a default date like the date of the first parent order.


Step 3: Map WP Swing Fields to WooCommerce Fields

WooCommerce Subscriptions stores data differently.
You need to match the WP Swing fields to WooCommerce meta fields.

Here is a useful mapping table:

WP Swing fieldWooCommerce Subscriptions field
subscription_idpost_id (created by importer)
start_date_schedule_start
next_payment_date_schedule_next_payment
billing_period_billing_period
billing_interval_billing_interval
statuspost_status
user_id_customer_user
product_idorder line item

If you do not map fields correctly, the subscription may import but renewals will break.


Step 4: Importing the Subscriptions

There are two ways to import:

1. Using a prepared CSV importer

Works only for basic cases. Good for small stores.

2. Using a custom script

This is the safest way for large stores or stores with many legacy subscriptions.

Here is a simple example code snippet that creates a subscription programmatically:

$subscription = wcs_create_subscription( array(
    'customer_id' => $customer_id,
    'start_date'  => $start_date,
    'next_payment' => $next_payment,
) );

$subscription->add_product( $product, 1, array(
    'total' => $price,
) );

$subscription->update_status( 'active' );

Below is an example of adding item meta:

$items = $subscription->get_items();

foreach ( $items as $item_id => $item ) {
    wc_add_order_item_meta( $item_id, '_billing_period', $period );
    wc_add_order_item_meta( $item_id, '_billing_interval', $interval );
}

This code needs to be customized for each store depending on the exported data.


Step 5: Testing Renewals

Testing renewals is the most important part. Here is what you should test before going live.

Test checklist

  • Does the subscription show the correct next payment date
  • Can Stripe or PayPal renew it
  • Is the customer charged correctly
  • Do renewal emails work
  • Does the subscription change status after renewal

To test Stripe renewals, you can use:

Test card: 4242 4242 4242 4242
Expiration: Any future date
CVC: Any 3 digits


Step 6: Switching From WP Swing to WooCommerce Subscriptions

Once you are sure all subscriptions have been imported correctly:

  1. Disable WP Swing Subscriptions
  2. Enable WooCommerce Subscriptions
  3. Check your cron events
  4. Refresh permalinks

You do not want both plugins active at the same time because they may conflict.


Step 7: Monitoring After Migration

For the first 7 days, watch renewal logs.
WooCommerce Subscriptions logs can be found in:

WooCommerce → Status → Logs → subscription logs

If you see errors like:

Renewal payment failed due to missing token

this means that some payment methods need manual update from the customer.

You can send them a simple message:

“Please log in and update your card details so your subscription continues without interruption.”


Common Problems During Migration

Here are the issues most stores run into.

Missing payment tokens

Stripe stores card data as tokens. These are usually not migrated and customers must update their cards.

Wrong timezones

If the timezone is wrong, the renewal date may shift by one day.

Old or deleted products

If a product no longer exists, you must create a new one and map it.

Duplicate subscriptions

If you import twice, you may have duplicates. You can write a script to detect duplicates by email address.

Example:

$subs = wcs_get_users_subscriptions( $user_id );

if ( count( $subs ) > 1 ) {
    // handle duplicates
}

FAQ Section


1. What is the safest way to migrate subscriptions from WP Swing to WooCommerce Subscriptions?

The safest way to move subscriptions from WP Swing to WooCommerce Subscriptions is a slow and controlled process where you check every step before importing anything into your live store. Most problems happen when people rush and try to import everything at once without testing.

A safe process looks like this. First, export all subscription data from WP Swing into a clean CSV file. Second, open that file in Google Sheets or Excel and fix everything that looks wrong, such as missing dates, wrong periods, or user accounts that no longer exist. Third, map every field from the CSV to the fields used by WooCommerce Subscriptions. They do not use the same structure, so this step is very important.

Once the data is ready, try importing only a few subscriptions on a test site. Turn on WooCommerce Subscriptions and renew one or two orders to see if the dates and payments work. When you confirm that renewals run correctly, import the rest of the subscriptions. Finally, monitor renewal logs for several days to make sure nothing breaks.

This slower approach may take longer, but it keeps your revenue safe and prevents failed payments or angry customers.


2. Do customers lose their saved payment methods during migration?

In most cases, yes, customers will lose their saved card details because payment gateways store these details as secure tokens that belong to the original plugin. These payment tokens usually cannot be copied from WP Swing to WooCommerce Subscriptions because they were created with a different data structure and a different plugin key.

This means Stripe or PayPal will not recognize those tokens after the migration. As a result, when the next renewal date arrives, WooCommerce Subscriptions will try to charge the customer but will fail because the card token is missing.

The easiest way to handle this is to notify customers in advance. You can tell them that your store is upgrading to a safer subscription system and that they will need to update their payment method once. When they log in, they can enter their card again, and WooCommerce Subscriptions will save a fresh token that works for future renewals.

Usually, over 90 percent of customers update their card within two or three days if you send a polite reminder. It is a normal part of any subscription system migration.


3. Can I migrate subscriptions without losing any revenue?

Yes, you can migrate subscriptions without losing money, but only if you plan the process carefully and test everything before you switch systems. The most important part is making sure that your next payment dates and billing intervals are correct. If these dates are wrong, customers might be charged too early, too late, or not at all.

To protect your revenue, follow these steps. First, make sure every subscription in your CSV has the correct next payment date. This date tells WooCommerce when to generate the next renewal order. Second, run a test migration on a staging site and trigger a renewal manually. See if the order is created and paid correctly. Third, once you import everything into your live site, check the subscription logs for at least one week. If you see any errors, correct them right away.

If you do this, the migration will be smooth and no customers will miss a payment cycle. The only exception is if payment tokens cannot be transferred, in which case you should remind customers to update their card.


4. Can I migrate expired or canceled subscriptions, or should I skip them?

You can migrate expired, canceled, or even paused subscriptions. In fact, it is useful to migrate them because they create a full and correct history inside WooCommerce Subscriptions. This history helps you understand customer lifetime value, churn rate, and past billing patterns.

Expired subscriptions also help identify customers who might want to resubscribe later. If customers see their old subscription in their account, they can renew it with a single click.

If you skip these older subscriptions, your reports may look incomplete. Also, WooCommerce Subscriptions may treat returning customers as new subscribers, which can lead to confusion.

Therefore, it is best to migrate all subscription records, even the old ones, as long as the data is clean and correct.


5. Do I need to recreate parent orders or can WooCommerce generate new renewals automatically?

You do not need to recreate old parent orders for most migrations. WooCommerce Subscriptions can generate new renewal orders automatically as long as the next payment date, billing period, and customer data are correct.

Parent orders are mostly used for history and reports. They show what the customer originally bought and how the subscription was created. If these orders exist in your store, WooCommerce will link the subscription to them. If they do not exist, the subscription will still work fine, but the history will be shorter.

The important part is not the parent order. The important part is the next payment date. As long as this date is valid, WooCommerce Subscriptions will create a new renewal order at the correct time.

If you want a perfect record, you can recreate parent orders using a script, but this is optional and usually not needed for normal store operations.


6. How long does a full migration take?

The time needed depends on the size of your store and the quality of your data. Small stores with fewer than 50 subscriptions can finish the migration in one or two hours, including testing. Medium stores with 100 to 500 subscriptions may need one or two days. Stores with more than 1000 subscriptions may need one week of preparation, cleanup, mapping, importing, and testing.

The most time is spent on data cleanup. If your export file contains missing dates, duplicate user records, or invalid values, you will spend more time fixing it. If everything is clean, the migration is fast.

Testing also takes time. You should test on a staging site, run a renewal, and then test again on the live site before disabling WP Swing.

So the full timeline usually looks like this:

Day 1: Export, cleanup, mapping
Day 2: Test import on staging
Day 3: Live import and verification
Days 4 to 7: Renewal monitoring

With a careful plan, the process is stress-free and predictable.


7. Will email notifications from WooCommerce Subscriptions work correctly after migration?

Yes, email notifications will work, but only if the subscriptions are imported with correct dates and statuses. WooCommerce Subscriptions uses these values to decide when to send each email, such as renewal reminders or payment failure notices.

If the next payment date is missing or wrong, the emails may not send on schedule. If the status is wrong, such as setting a subscription to on-hold when it should be active, then the wrong email may be sent.

The best way to confirm that emails work is to test a renewal after the import. When WooCommerce generates a renewal order, it will also send the correct email. You can also use the Email Test tool inside WooCommerce settings to check whether your templates are correct.

Make sure your SMTP service (such as SendGrid, Mailgun, Brevo, or WP Mail SMTP) is working, since WooCommerce depends on it for sending emails reliably.


8. Can I migrate subscriptions that include coupon discounts or special prices?

Yes, you can migrate subscriptions that include discounts, trial periods, or custom pricing. You only need to make sure that the correct price is applied when you add the subscription item in the import process.

In a CSV import, you can set a custom price for the line item by using the price field. In a custom script, you can use something like this:

$subscription->add_product( $product, 1, array(
    'total' => $discounted_price
) );

WooCommerce Subscriptions will respect this price for future renewals.
If the discount is meant to apply only once, you may need an extra line item meta field to stop the discount after the first renewal.

Always test one discounted subscription after importing to make sure the logic behaves the way you expect.


9. Can I run WP Swing Subscriptions and WooCommerce Subscriptions at the same time?

No, you should not run both plugins at the same time. They both try to manage subscriptions, and they use different database structures. If both are active, they may create duplicate scheduled events, renewals may fail, and customer accounts may show incorrect subscription data.

The correct process is to finish the import, verify that everything works, then disable WP Swing before enabling WooCommerce Subscriptions. This ensures that there is no conflict and that only one plugin is in charge of renewals.

Running both at once can also cause confusion for customers because they may see two subscriptions for the same product. It can also lead to double charges if both plugins try to renew on the same date.

Always keep only one subscription system active.


Summary

Migrating Subscriptions from WP Swing to WooCommerce
Migrating Subscriptions from WP Swing to WooCommerce

Moving from WP Swing Subscriptions to WooCommerce Subscriptions is a smart step for any store that depends on recurring payments. With careful mapping, clean data, and good testing, you can move all of your subscribers without losing revenue.

 

How to Migrate Your Typepad to WordPress Before the Shutdown

The Clock Is Ticking –  migrate your Typepad to WordPress

For almost twenty years, **Typepad** has been the home of countless bloggers, hobbyists, and small businesses. It was one of the earliest platforms to make blogging accessible, and many creators have built a legacy there.

But time is running out. With the **official shutdown scheduled for September 30, 2025**, Typepad blogs will soon vanish unless action is taken. This deadline is not just about technology — it’s about protecting your voice, your content, and years of effort.

The good news? You can save everything by migrating to **WordPress**, the world’s most popular website platform. WordPress is secure, flexible, SEO-friendly, and future-proof.

This guide walks you through the entire process — from exporting your content to importing it into WordPress, fixing broken images, preserving SEO, and redesigning your site for growth.


Why WordPress Is the Best Destination

When a platform shuts down, you’re faced with choices: Ghost, Squarespace, Wix, Substack, or even just saving everything offline. But WordPress consistently stands out here’s why:

  1. Ownership – Your content is yours. No company shutdown can erase it.
  2. SEO power – Google loves WordPress’s clean structure and metadata options.
  3. Flexibility – Tens of thousands of themes and plugins let you build any type of site.
  4. Scalability – Works for a one-person blog or a full-scale digital magazine
  5. Community – Millions of users, developers, and resources at your fingertips.

If you want your blog to not only survive but grow, WordPress is the logical new home.

 

Typepad Blog to WordPress

Step 1: Export Your Blog from Typepad

Before Typepad closes its doors, export your data.

1. Log in to your Typepad dashboard.
2. Navigate to Settings → Import/Export.
3. Click Export to download your `.txt` archive. This file contains your posts, categories, and comments.
4. Download your images and attachments. Depending on how your blog was set up, they may be bundled or require manual download.
5. Save everything in multiple places (computer, external drive, and cloud storage).

⚠️ Pro Tip: Even if you’re not ready to migrate right now, export today. After September 30, 2025, you may lose access to your content forever.

 

 Step 2: Prepare Your New WordPress Site

With your Typepad export ready, it’s time to set up WordPress.

Choose a Hosting Provider

Good hosting ensures speed, security, and reliability. Popular options include:

  • Hostinger – Affordable and beginner-friendly.
  • Kinsta – Premium managed hosting for top performance, but really expensive

Install WordPress

Most hosting providers offer one-click WordPress installs. In minutes, your new site will be live.

Pick a Theme

Choose a lightweight, SEO-friendly theme:

  • Astra – Fast and flexible.
  • GeneratePress – Minimalist and reliable.
  • Kadence – Excellent for bloggers.

Install Key Plugins

  • Rank Math SEO** (or Yoast SEO) – Optimize search presence.
  • Redirection – Manage 301 redirects from old URLs.
  • Classic Editor – Helpful for fixing formatting.
  • Auto Upload Images** – Relinks image paths automatically.

Step 3: Import Your Typepad Content

Now transfer your exported content.

1. In WordPress, go to **Tools → Import**.
2. Select **Movable Type and Typepad Importer**.
3. Upload your `.txt` file.
4. Assign authors where needed.
5. Verify categories, tags, and comments.

This step usually works smoothly, but larger blogs may take longer.

Need Expert Help with Migrating Typepad to WordPress?

Hire a certified WordPress expert from Codeable to help you move your Typepad blog safely to WordPress with all posts, images, and SEO intact.

Get a Free Estimate

 Step 4: Fix Images and Media

One of the most common migration issues is broken images.

How to solve broken images during Typepad migration

  • Upload your images into the WordPress `/wp-content/uploads/` folder.
  • Use the Auto Upload Images plugin to automatically relink them.
  • Manually check featured images and older posts.

Restoring visuals is crucial because images carry both emotional, content and SEO weight.

Step 5: Preserve Your SEO

SEO preservation is non-negotiable if you want to maintain traffic.

Steps:

1. Map old URLs to new ones.

* Example:

* Old: `http://yourblog.typepad.com/2020/05/my-post.html`
* New: `https://yourblog.com/my-post/`
2. Use the **Redirection plugin** to set up permanent (301) redirects.
3. Update your sitemap and resubmit it in **Google Search Console**.
4. Monitor traffic and errors in Search Console.

Done correctly, you won’t lose rankings — you may even gain them.

 Step 6: Redesign & Customize

Migration is also an opportunity for a **fresh design**.

* Customize fonts, colors, and layouts through your theme.
* Add must-have pages: **About, Contact, Privacy Policy**.
* Use widgets to display **Recent Posts**, **Categories**, or an **Email Signup Form**.
* Consider tools like **Google Analytics** or **Microsoft Clarity** to track engagement.

Step 7: Test & Launch

Before announcing your migration, test thoroughly.

  • Check your site on **desktop, tablet, and mobile**.
  • Test forms, menus, and links.
  • Verify redirects work.
  • Optimize speed with caching (WP Rocket, LiteSpeed Cache).

Only after testing should you publicly announce the new site.

 Common Issues and Fixes

  • Formatting problems – Use the Classic Editor to tidy up.
  • Missing comments – Double-check export and re-import.
  • Duplicate posts – Delete extras manually.
  • Slow load speed – Optimize images and use a CDN.

Future-Proofing Your WordPress Blog

Once you’ve migrated, protect your investment:

  1.  Keep **WordPress, plugins, and themes updated**.
  2. Set up **automatic backups** (UpdraftPlus, AllInOneMigration).
  3. Continue publishing valuable content for SEO growth.
  4. Engage readers with **newsletters and social sharing tools**.

Why You Should Act Now

The shutdown date may feel far away, but migration projects often take longer than expected. By acting early, you avoid:

  • Last-minute panic if servers slow down near the deadline.
  • SEO loss due to rushed redirects.
  • Data gaps if you miss files during export.

Early movers also benefit from the chance to redesign and optimize without pressure.

The September 30, 2025 shutdown is a hard deadline. Waiting puts your content at risk.

Migrating to WordPress ensures your posts, images, comments, and SEO survive — and thrive in a modern, flexible platform.

Whether you do it yourself with this guide or hire an expert, the key is to act now.

Need Expert Help with Migrating Typepad to WordPress?

Hire a certified WordPress expert from Codeable to help you move your Typepad blog safely to WordPress with all posts, images, and SEO intact.

Get a Free Estimate

Frequently Asked Questions About Migrating from Typepad to WordPress

1. When exactly is Typepad shutting down, and what happens after that date?
Typepad will officially shut down on September 30, 2025. After this date, the platform will no longer be accessible, meaning you won’t be able to log in, view, or manage your blog. If you don’t export your content before the shutdown, there’s a high chance it will be lost permanently. That’s why it’s critical to create backups and start your migration process well before the deadline. Migrating early also gives you time to test your new WordPress site without pressure.

2. Can I migrate my comments, images, and categories along with my posts?
Yes, WordPress supports importing not just blog posts but also comments, categories, and tags from your Typepad export file. Images are trickier — while many transfer automatically, some may break because of different storage paths. Fortunately, plugins like Auto Upload Images can repair those links, and manual uploads can fix any missing files. Spending time on this ensures your new site feels complete and consistent, preserving both the look and the community feel of your blog.

3. Will migrating to WordPress hurt my SEO rankings?
Not if you take the right steps. SEO is often tied to your URL structure, so the key is setting up proper 301 redirects from your old Typepad URLs to your new WordPress URLs. This tells Google and other search engines that your content has moved but still exists, protecting your authority and rankings. In some cases, a well-optimized WordPress setup can even improve your SEO performance thanks to faster load times, better mobile support, and enhanced metadata control.

4. How long does it usually take to migrate a blog from Typepad to WordPress?
The timeline depends on the size of your blog and your comfort with WordPress. A smaller blog with a few hundred posts can often be migrated in a single afternoon. Larger sites with thousands of entries, images, and comments may take a couple of days, especially if you’re fixing formatting or image issues. If you’re doing the migration yourself for the first time, give yourself extra time for testing and troubleshooting. Hiring an expert can shorten the process dramatically since they already know how to handle common pitfalls.

5. Should I consider hiring a WordPress expert, or is DIY good enough?
If you’re comfortable with technical setups, backups, and troubleshooting, you can absolutely migrate your blog on your own using this guide. However, if your blog is large, has complex formatting, or generates income, hiring a WordPress migration expert is often worth it. Experts ensure no posts or images are lost, all SEO redirects are properly configured, and your new site looks polished from day one. For many bloggers, the peace of mind and saved time outweigh the cost of professional help.

6. What if my Typepad export file is corrupted or incomplete?
Occasionally, export files may fail or skip certain content, especially if your blog is very large. The first step is to try the export process again and check if the file size changes. If problems persist, you may need to split your blog into smaller exports or use a manual copy-paste approach for certain posts. In the worst case, a migration expert can often use advanced tools to recover most of your data. That’s why it’s best to export as soon as possible, giving you time to check the files well before the shutdown.

7. Will all my old blog links shared on social media still work?
Not automatically. If someone clicks an old Typepad link after the shutdown, it will lead to an error unless you’ve set up redirects. By mapping old URLs to your new WordPress site, you ensure that readers following old links land on the correct post. This is especially important if your blog has backlinks from other websites, since losing those could harm your SEO. With proper redirects, your blog’s traffic remains intact, and your readers won’t notice a disruption.

8. Can I redesign my site during the migration process, or should I wait?
One of the best parts of moving to WordPress is the opportunity to modernize your design. You can absolutely launch with a new theme, better navigation, and an updated layout. In fact, many bloggers use migration as a chance to refresh their brand and improve user experience. That said, if you’re pressed for time, focus first on getting all your content migrated and SEO preserved — design updates can always follow later once your content is secure.

9. What if I already have a custom domain pointing to my Typepad blog?
If you’ve been using a custom domain (like yourblog.com) with Typepad, migration becomes easier. Once your WordPress site is set up, you can point that domain to your new hosting provider. This way, your readers will continue visiting the same URL, but it will now load your WordPress site instead of Typepad. If you don’t have a custom domain yet, consider registering one — it gives you independence from any blogging platform in the future.

10. Is WordPress difficult to manage after migration?
Not at all. While WordPress offers a huge amount of flexibility, the basics — writing posts, uploading images, and managing comments — are very straightforward. If you could use Typepad, you can learn WordPress quickly. There’s also a massive library of tutorials, forums, and documentation available. Plus, unlike Typepad, WordPress will continue evolving and improving, so you won’t face another sudden shutdown.

How to fix: ACF now automatically escapes unsafe HTML when rendered by the_field or the ACF shortcode

Escaping the Maze: Mastering ACF’s New HTML Escape Mechanics 🚀

Hello, fellow WordPress aficionados! 🌟 Let’s talk about a game-changer in our beloved ACF PRO that’s causing both excitement and a bit of head-scratching in the community. Yes, you guessed it: ACF now automatically escapes unsafe HTML when rendered by the_field() or the ACF shortcode. Fear not! I’m here to demystify this update and arm you with the knowledge (and code) to tackle any challenges head-on.

Quick Recap: What’s ACF PRO Again? 🧐

For the uninitiated, Advanced Custom Fields (ACF) PRO is the powerhouse behind customizing WordPress sites, allowing you to add custom fields to your pages, posts, and even custom post types. It’s like giving your car a nitro boost but for your website.

The Update: Safety First! 🔐

ACF PRO’s latest update is like a superhero upgrade for your site’s security, automatically escaping unsafe HTML in fields. This means that it helps prevent nasty things like XSS attacks by ensuring that only clean, safe HTML is output through your custom fields.

  • The Update in a Nutshell: Automatically escapes unsafe HTML.
  • Affected Functions: the_field(), ACF shortcode.
  • Why It Matters: Enhances security, and minimizes XSS attack risks.

ACF will soon escape unsafe HTML that is rendered by the_field()

Breaking it Down: The Impact 🎯

So, what does this mean for you, the developer, designer, or site owner? Let’s dissect:

  • Pros: Enhanced security, peace of mind, reduced plugin reliance for sanitization.
  • Cons: Potential impact on fields that intentionally output HTML for functionality.

Looking to resolve the issue of unsafe HTML rendering with ACF PRO? Get expert assistance from Codeable’s WordPress developers today!

Find Developer

The Solution Space: Adapting to Change 🛠

Fear not! Adapting is our forte. Here’s how you can embrace this update without breaking a sweat:

1. Understanding the Change


// Before the update
echo get_field('custom_html_field');

// After the update
echo htmlspecialchars(get_field('custom_html_field'), ENT_QUOTES, 'UTF-8');


 

2. Safe HTML Output

If your field needs to output HTML safely, consider using wp_kses_post():

echo wp_kses_post(get_field('custom_html_field'));

 

3. Custom Sanitization

Need more control? Roll out your custom sanitization function:

function my_custom_sanitizer($content) {
   // Custom sanitization logic here
   return $content;
}

echo my_custom_sanitizer(get_field('custom_html_field'));

 

4. Whitelisting HTML Tags

Use wp_kses() to allow specific tags:

$allowed_tags = [
    'a' => [
        'href' => [],
        'title' => []
    ],
    'br' => [],
    'em' => [],
    'strong' => [],
];

echo wp_kses(get_field('custom_html_field'), $allowed_tags);

 

Navigating ACF PRO’s HTML Escape Functionality 🧭

Deep Dive: The the_field() Conundrum

Imagine you’ve got a custom field designed to embed YouTube videos directly into your posts. Previously, you’d add the iframe into your ACF field, and voila, it’d render seamlessly. Now, with automatic escaping in play, your iframe turns into a visible chunk of HTML code, rather than the intended video player.

The Problem:


<!-- What you entered in ACF -->
<iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

<!-- What renders on your site -->
&lt;iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen&gt;&lt;/iframe&gt;

The Solution:

Leverage WordPress’ wp_oembed_get() to safely embed videos, bypassing the need to directly input iframes into ACF fields:



// Fetch video URL from ACF field
$video_url = get_field('video_url');

// Use WordPress oEmbed functionality
echo wp_oembed_get($video_url);


 

 

This method ensures your embeds remain functional, sidestepping direct HTML input and keeping your site secure.

Scenario 2: Custom HTML in Text Fields

You’re using ACF to add custom HTML content to a page—perhaps a uniquely styled call-to-action (CTA) block. Post-update, your HTML is being escaped, stripping away the intended design and functionality.

Before the Update:


<div class="cta-block">
   <?php the_field('custom_html_cta'); ?>
</div>

 

Adapting:

Option 1: Use wp_kses_post() for Basic HTML

For basic HTML elements:


<div class="cta-block">
    <?php echo wp_kses_post(get_field('custom_html_cta')); ?>;
</div>

 

Option 2: Custom Allow-List with wp_kses()

When specific HTML elements and attributes are needed:


$allowed_html = array(
    'div' => array(
        'class' => array(),
    ),
    'a' => array(
        'href' => array(),
        'class' => array(),
        'title' => array(),
    ),
    'span' => array(
        'class' => array(),
    ),
    // Add more tags and attributes as needed
);

echo wp_kses(get_field('custom_html_cta'), $allowed_html);


Advanced Use Case: Dynamic Content with ACF and JavaScript

You’re injecting JavaScript via ACF fields for dynamic content customization. The update complicates direct script injection due to automatic escaping.

The Safe Path Forward:

Enqueue Scripts Properly

  1. Store your JavaScript code in external .js files.
  2. Enqueue these scripts using wp_enqueue_script() within your theme’s functions.php, or trigger them conditionally within your template files.

// Example: Enqueuing a custom script
function my_custom_scripts() {
    if (get_field('activate_custom_behavior', 'option')) { // Assuming 'option' page setting
        wp_enqueue_script('my-custom-script', get_template_directory_uri() . '/js/my-custom-script.js', array('jquery'), null, true);
    }
}
add_action('wp_enqueue_scripts', 'my_custom_scripts');


You can also use ACF fields to pass configuration or data to these scripts via localized script variables (wp_localize_script()).

// Localize script with data from ACF fields
function my_localized_script_data() {
    wp_localize_script('my-custom-script', 'MyScriptParams', array(
        'dynamicData' => get_field('dynamic_data', 'option'),
    ));
}
add_action('wp_enqueue_scripts', 'my_localized_script_data');

Given the constraints and the nature of your request, I’ll extend the content with more examples and delve deeper into practical scenarios. Let’s get into the nitty-gritty of working around ACF PRO’s HTML auto-escape functionality, ensuring your WordPress projects remain both dynamic and secure.

Navigating ACF PRO’s HTML Escape Functionality 🧭
Deep Dive: The the_field() Conundrum
Imagine you’ve got a custom field designed to embed YouTube videos directly into your posts. Previously, you’d add the iframe into your ACF field, and voila, it’d render seamlessly. Now, with automatic escaping in play, your iframe turns into a visible chunk of HTML code, rather than the intended video player.

The Problem:

<!-- What you entered in ACF -->
<iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

<!-- What renders on your site -->
&lt;iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen&gt;&lt;/iframe&gt;

The Solution:
Leverage WordPress’ wp_oembed_get() to safely embed videos, bypassing the need to directly input iframes into ACF fields:


// Fetch video URL from ACF field
$video_url = get_field('video_url');

// Use WordPress oEmbed functionality
echo wp_oembed_get($video_url);

This method ensures your embeds remain functional, sidestepping direct HTML input and keeping your site secure.

Scenario 2: Custom HTML in Text Fields
You’re using ACF to add custom HTML content to a page—perhaps a uniquely styled call-to-action (CTA) block. Post-update, your HTML is being escaped, stripping away the intended design and functionality.

Before the Update:


<div class="cta-block">
    <?php the_field('custom_html_cta'); ?>
</div>

Adapting:
Option 1: Use wp_kses_post() for Basic HTML

For basic HTML elements:

<div class="cta-block">
    <?php echo wp_kses_post(get_field('custom_html_cta')); ?>
</div>

Option 2: Custom Allow-List with wp_kses()

When specific HTML elements and attributes are needed:


$allowed_html = array(
    'div' => array(
        'class' => array(),
    ),
    'a' => array(
        'href' => array(),
        'class' => array(),
        'title' => array(),
    ),
    'span' => array(
        'class' => array(),
    ),
    // Add more tags and attributes as needed
);

echo wp_kses(get_field('custom_html_cta'), $allowed_html);

Advanced Use Case: Dynamic Content with ACF and JavaScript
You’re injecting JavaScript via ACF fields for dynamic content customization. The update complicates direct script injection due to automatic escaping.

The Safe Path Forward:
Enqueue Scripts Properly

Store your JavaScript code in external .js files.
Enqueue these scripts using wp_enqueue_script() within your theme’s functions.php, or trigger them conditionally within your template files.

// Example: Enqueuing a custom script
function my_custom_scripts() {
    if (get_field('activate_custom_behavior', 'option')) { // Assuming 'option' page setting
        wp_enqueue_script('my-custom-script', get_template_directory_uri() . '/js/my-custom-script.js', array('jquery'), null, true);
    }
}
add_action('wp_enqueue_scripts', 'my_custom_scripts');

Use ACF fields to pass configuration or data to these scripts via localized script variables (wp_localize_script()).


// Localize script with data from ACF fields
function my_localized_script_data() {
    wp_localize_script('my-custom-script', 'MyScriptParams', array(
        'dynamicData' => get_field('dynamic_data', 'option'),
    ));
}
add_action('wp_enqueue_scripts', 'my_localized_script_data');

This approach maintains security while offering dynamic, JavaScript-driven content customization.

Embracing Change: A Path Forward

The transition to automatic HTML escaping in ACF PRO represents a significant shift towards enhancing security and reliability in WordPress development. By adapting your workflows to embrace these changes—leveraging WordPress core functions for sanitization, and strategically managing HTML and JavaScript content—you ensure your projects remain both innovative and secure.

While the journey may require rethinking certain practices, the destination—a more secure, dynamic web—is undoubtedly worth it. Armed with these strategies and examples, you’re well-equipped to navigate the nuances of ACF PRO’s latest update, transforming potential obstacles into opportunities for growth and innovation.

FAQs 🚀

  • Q: Will this break my site?
    • A: Not necessarily. Test your fields, especially those outputting HTML.
  • Q: Can I disable this feature?
    • A: It’s not recommended due to security concerns, but customizing output methods can bypass automatic escaping.
  • Q: What if I need to output JavaScript?
    • A: Carefully. Consider enqueuing scripts rather than embedding them directly.

Looking to resolve the issue of unsafe HTML rendering with ACF PRO? Get expert assistance from Codeable’s WordPress developers today!

Find Developer

Wrapping Up: Secure, Customize, Thrive 🌟

This update is a significant step toward more secure, robust WordPress sites. With the tips and tricks shared, you’re well-equipped to adapt and continue creating dynamic, interactive, and safe web experiences.

Stay curious, stay secure, and most importantly, stay awesome! 💪

 

How to Fix ACF Will Soon Escape Unsafe HTML That is Rendered by the_field()

How to Fix ACF Will Soon Escape Unsafe HTML That is Rendered by the_field()

Advanced Custom Fields (ACF) PRO is a powerful plugin for WordPress developers, allowing them to easily create custom fields and meta boxes for their websites. However, like any tool, it’s essential to use ACF PRO correctly to avoid potential security risks. One such risk involves the rendering of unsafe HTML when using the_field() function, which can leave your site vulnerable to cross-site scripting (XSS) attacks and other security threats. In this article, we’ll delve into this issue and provide practical solutions to fix it.

Looking to resolve the issue of unsafe HTML rendering with ACF PRO? Get expert assistance from Codeable’s WordPress developers today!

Find Developer

Unsafe HTML rendering in ACF can pose a security risk, leaving your website vulnerable to attacks. However, with the advancements in their development process, ACF is soon to introduce a fix that will eliminate this concern. By incorporating this solution, you can enjoy a safer and more secure user experience on your website.

ACF will soon escape unsafe HTML that is rendered by the_field()

To help you understand how to implement this fix, we will provide you with clear and concise code examples. Whether you are a developer or simply interested in understanding the technical side of ACF, this article has got you covered. Join us as we explore the steps to fix the ACF issue and ensure the safety of your website’s HTML rendering.

Understanding the issue with ACF and unsafe HTML

ACF is a powerful WordPress plugin that allows you to create custom fields and easily add them to your website. However, a common problem with ACF arises when using the_field() function to display the data stored in these custom fields. The function does not escape the HTML output by default, which can lead to potential security vulnerabilities.

When HTML tags and special characters are not properly escaped, it allows malicious users to inject harmful code into your website, leading to cross-site scripting (XSS) attacks. These attacks can result in stolen data, defacement of your website, or even complete control by the attacker.

The impact of unsafe HTML on your website

The impact of unsafe HTML rendering can be severe, affecting both the functionality and security of your website. Let’s take a closer look at the potential consequences:

  1. Security vulnerabilities: As mentioned earlier, unsafe HTML can allow attackers to inject malicious code into your website. This can result in data breaches, unauthorized access, and other security-related issues.
  2. User experience: Unsafe HTML can disrupt the user experience on your website. If the injected code interferes with the layout or functionality, it can lead to a poor user experience, causing frustration and potentially driving visitors away.
  3. Search engine optimization: Search engines may penalize your website if it contains unsafe HTML. This can negatively impact your search engine rankings and overall visibility online.

Introducing the ACF Will Soon Escape Unsafe HTML error

ACF has acknowledged the issue with unsafe HTML rendering and is actively working on a solution. In their upcoming release, they will introduce a new feature called “ACF Will Soon Escape Unsafe HTML.” This feature aims to automatically escape HTML output by default when using the_field() function, providing a safer environment for your website.

The “ACF Will Soon Escape Unsafe HTML” error is a warning message that developers may encounter when using the_field() function without proper HTML escaping. It serves as a reminder to update your code and ensure that the HTML output is secure.

Why the_field() function triggers this error

The_field() function, by default, does not escape the HTML output. This means that any HTML tags or special characters within the custom field data will be rendered as-is, without any encoding or escaping. While this may be convenient for some scenarios, it can pose a significant security risk if the data is not trusted or sanitized.

To address this issue, ACF has decided to introduce the “ACF Will Soon Escape Unsafe HTML” error. This serves as a proactive measure to encourage developers to update their code and ensure the proper escaping of HTML output.

Code examples of the_field() function causing the error

Let’s take a look at some code examples to understand how the_field() function can trigger the “ACF Will Soon Escape Unsafe HTML” error:

Example 1:

<?php 
    $field_value = get_field('my_custom_field'); 
    echo the_field('my_custom_field'); 
?>

In this example, the_field() function is used to output the value of the custom field ‘my_custom_field’. However, if the field contains unsafe HTML or special characters, the function will not escape them by default, triggering the error.

Example 2:

<?php $field_value = get_field('my_custom_field'); echo 'div>' . the_field('my_custom_field') . '/div>'; ?>

In this example, the_field() function is used within an HTML element. If the custom field contains unsafe HTML, it will be rendered as-is within the div element, triggering the error.

How to fix the ACF Will Soon Escape Unsafe HTML error

Now that we understand the issue and how it can occur, let’s explore three methods to fix the “ACF Will Soon Escape Unsafe HTML” error and ensure the safety of your HTML rendering.

Method 1: Using the update_field() function

One way to fix the “ACF Will Soon Escape Unsafe HTML” error is by using the update_field() function instead of the_field(). The update_field() function allows you to retrieve and escape the HTML output from your custom field, ensuring that it is safe for rendering.

Here’s an example of how you can implement this method:

<?php 
    $field_value = get_field('my_custom_field'); 
    $escaped_field_value = esc_html($field_value); 
    echo $escaped_field_value;
 ?>

In this example, we first retrieve the value of the custom field using the get_field() function. Then, we use the esc_html() function to escape the HTML output, ensuring that any unsafe HTML or special characters are properly encoded. Finally, we echo the escaped field value, which can now be safely rendered on your website.

Method 2: Customizing the output with htmlspecialchars()

Another method to fix the “ACF Will Soon Escape Unsafe HTML” error is by customizing the output using the htmlspecialchars() function. This function allows you to encode special characters within your custom field data, preventing them from being interpreted as HTML.

Here’s an example of how you can implement this method:

<?php
    $field_value = get_field('my_custom_field');
    $encoded_field_value = htmlspecialchars($field_value);
    echo $encoded_field_value; 
?>

In this example, we retrieve the value of the custom field using the get_field() function. Then, we use the htmlspecialchars() function to encode any special characters within the field value. This ensures that the HTML output is safe and prevents any potential security vulnerabilities.

Method 3: Using the_field() with the ‘esc_html’ filter

The third method to fix the “ACF Will Soon Escape Unsafe HTML” error is by using the_field() function with the ‘esc_html’ filter. This filter allows you to automatically escape the HTML output without modifying the original field value.

Here’s an example of how you can implement this method:

<?php 
    $field_value = get_field('my_custom_field'); 
    echo apply_filters('the_field', $field_value, null, 'esc_html'); 
?>

In this example, we retrieve the value of the custom field using the get_field() function. Then, we use the apply_filters() function to apply the ‘esc_html’ filter to the_field() function. This ensures that the HTML output is properly escaped, providing a safer rendering of the custom field value.

Conclusion

Unsafe HTML rendering in ACF can pose a significant security risk to your website. However, with the upcoming release of “ACF Will Soon Escape Unsafe HTML,” you can ensure a safer and more secure user experience. By implementing the code examples provided in this article, you can fix the “ACF Will Soon Escape Unsafe HTML” error and protect your website from potential attacks.

Remember to always prioritize the security and integrity of your website’s HTML rendering. Stay updated with the latest ACF releases and best practices to ensure a secure and reliable user experience for your visitors.

Looking to resolve the issue of unsafe HTML rendering with ACF PRO? Get expert assistance from Codeable’s WordPress developers today!

Find Developer

Understanding the “ACF PRO — ACF Will Soon Escape Unsafe HTML” Warning

ACF will soon escape unsafe html that is rendered by the_field()

This warning means that Advanced Custom Fields (ACF), a popular WordPress plugin, will soon start escaping unsafe HTML input to prevent security issues.

Why is ACF adding this security feature?

ACF wants to prevent unwanted HTML and JavaScript from being executed when field values are rendered in the frontend. Without this security check, it’s possible for malicious users to input code that could compromise your site.

How will this affect my site?

Any field values that contain HTML will have special characters escaped to render as plain text instead. For example:

echo $value; 
// Before: &lt;wp-p&gt;Hello&lt;/wp-p&gt;;
// After: &amp;amp;lt;p&amp;amp;gt;Hello&amp;amp;lt;/p&amp;amp;gt;

This prevents the HTML from being executed.

What should I do about “ACF Will Soon Escape Unsafe HTML” Warning?

You have three options:

1. Sanitize your field values before rendering.

Use a function like wp_kses_post() to strip unwanted HTML tags and attributes, keeping only allowed ones.

For example:

$sanitized_value = wp_kses_post( $value );
echo $sanitized_value;

This will fix the warning and allow your desired HTML to be rendered safely.

2. Get help from WordPress Developers

Trust the expertise of Codeable’s seasoned WordPress developers to implement robust solutions and fortify your site against potential threats. With their in-depth knowledge and meticulous attention to detail, they’ll ensure that your ACF PRO implementation is not only secure but also optimized for performance and functionality. Reach out to Codeable today and safeguard your WordPress site with confidence.

3. Do nothing

If you don’t use HTML in your ACF field values, this update won’t affect you.

Looking to resolve the issue of unsafe HTML rendering with ACF PRO? Get expert assistance from Codeable’s WordPress developers today!

Find Developer

 

Why You’re Seeing This Warning in WordPress

If you’ve recently updated Advanced Custom Fields (ACF) and started seeing warnings about “ACF PRO Will Soon Escape Unsafe HTML,” don’t panic. This is actually a helpful notice from ACF to let you know that some of your field values may contain unsafe HTML that could put your site at risk.

What is “Unsafe HTML”?

Unsafe HTML refers to HTML tags, attributes or code that could potentially be exploited for malicious purposes like XSS (cross-site-scripting) attacks. Some examples of unsafe HTML that will trigger the ACF warning include:

<script>alert(“Hi!”)</script> <a href=”javascript:alert(‘XSS’);”>Click me</a>

To prevent these kinds of vulnerabilities, ACF PRO will be escaping unsafe values in upcoming versions. Escaping means converting unsafe HTML into plain text so it’s not executed as code.

How to Fix the Warning

To fix this warning and ensure your ACF fields don’t contain unsafe HTML, you have two options:

  1.  Manually clean up unsafe values Go through your ACF fields and sanitize any values containing unsafe HTML. Replace or remove HTML tags and attributes, leaving only plain text.
  1. Enable “Escape HTML” on your fields The easiest option is to enable the “Escape HTML” setting on any fields that may contain unsafe values. This will automatically sanitize the values, escaping unsafe HTML.

To enable “Escape HTML” on your fields:

  • Edit the field group
  • Click on the field you want to edit
  • Under “Field Options,” check the box next to “Escape HTML”
  • Save your changes

This will escape unsafe HTML in both existing and new values for that field going forward. Repeat this for any other fields as needed.

ACF will soon escape unsafe HTML that is rendered by the_field()

The Risks of Rendering Unsanitized HTML

Unsanitized HTML refers to user-inputted HTML that hasn’t been properly filtered for malicious code before being displayed on your website. Allowing unsanitized HTML to be rendered poses serious security risks.

Cross-Site Scripting (XSS) Attacks

The biggest danger of rendering unsanitized HTML is that it opens you up to XSS attacks. An attacker could input JavaScript, PHP, or other code into a form on your site. If that input is displayed without sanitizing, the code will execute on your site. This allows the attacker to do things like:

  • Steal cookies and session data
  • Redirect users to malicious sites
  • Change or delete site content
  • Launch denial-of-service attacks

To prevent XSS attacks, you must sanitize all user input before displaying it. For HTML input, use a library like HTML Purifier to filter out unsafe tags and attributes.

Injected Malware

Rendering unsanitized HTML also makes it possible for attackers to inject malicious scripts, iframes, and other HTML elements containing malware. Even if the input isn’t specifically targeting your site, rendering it could infect your users with malware like:

  • Ransomware that encrypts user files until a ransom is paid
  • Cryptocurrency mining scripts that hijack CPU power
  • Keylogging or form-grabbing code to steal user data

SEO and Accessibility Issues

Allowing unfiltered HTML input can also cause problems for search engines and accessibility tools. Unsemantic markup, duplicate content, and hidden text can confuse search engine crawlers. And elements like <blink>, <marquee>, and <font> can disrupt screen readers and other assistive technologies.

How to Fix “ACF PRO — ACF Will Soon Escape Unsafe HTML”

If you see this warning from ACF PRO, it means you have HTML in a field that could potentially contain malicious code. To fix this, you’ll need to sanitize the HTML to strip out anything unsafe.

Use esc_html()

The easiest way to sanitize HTML in ACF is to use the esc_html() function. This will strip out any HTML tags and encode special characters to make the string safe to display.

For example, if you have a text field with this HTML: <p><a href=”http://example.com”>Link</a></p>

You can display it safely like this:

echo esc_html( $field['value'] );


This will output: <p><a href=”http://example.com”>Link</a></p>

Allow Specific Tags

If you want to allow some HTML tags but not others, use wp_kses_post(). This lets you pass an array of allowed tags.

For example, to allow links and emphasis tags:

$allowed_tags = array(
    'a' =&amp;amp;amp;amp;gt; array(
        'href' =&amp;amp;amp;amp;gt; true
    ),
    'em' =&amp;amp;amp;amp;gt; true 
);

echo wp_kses_post( $field['value'], $allowed_tags );

This will strip out any tags not in the allowed_tags array, sanitizing the input.

Use ACF’s sanitize_callback

The best way to sanitize an ACF field is to use the sanitize_callback argument. You can pass a callback function that will be run whenever the field is saved.

For example:

'fields' =&amp;amp;amp;amp;gt; array(
    array(
        'key'           =&amp;amp;amp;amp;gt; 'html_field',
        'label'         =&amp;amp;amp;amp;gt; 'HTML Field',
        'name'          =&amp;amp;amp;amp;gt; 'html_field',
        'type'          =&amp;amp;amp;amp;gt; 'wysiwyg',
        'sanitize_callback' =&amp;amp;amp;amp;gt; 'my_acf_sanitize_html' 
    )
)

function my_acf_sanitize_html( $input ) {
    $allowed_html = array(
        'a' =&amp;amp;amp;amp;gt; array( 'href' =&amp;amp;amp;amp;gt; true ),
        'em' =&amp;amp;amp;amp;gt; true,
        'strong' =&amp;amp;amp;amp;gt; true
    );
    return wp_kses_post( $input, $allowed_html );
} 

This will run the my_acf_sanitize_html() function whenever the html_field is saved, sanitizing the input.

 

Using Esc_html() and Esc_attr() to Sanitize Output

To fix the “ACF PRO Will Soon Escape Unsafe HTML” warning, you’ll need to sanitize all output in your ACF fields. This means escaping HTML characters so they are not executed as code. ACF provides two helper functions for this:

esc_html()

Use esc_html() to sanitize output that will be displayed in the HTML body. This escapes characters like <, >, “, ‘, etc. For example:

echo esc_html( $your_string );

 

esc_attr()

Use esc_attr() to sanitize output used in HTML attributes like src, href, value, etc. For example:

echo '&lt;a href="' . esc_attr( $your_string ) . '"&gt;Link&lt;/a&gt;';
[php]

&lt;h2&gt;Examples of Escaping ACF Values Before Output&lt;/h2&gt;
To fix this warning, you'll need to properly escape ACF field values before outputting them. This means converting characters that could be misinterpreted as HTML into HTML entities.

For example, to output a field named &lt;code&gt;my_text&lt;/code&gt;, you'd use:
[php]
echo esc_html( get_field('my_text') );

The esc_html() function will escape things like <, >, “, ‘, and &. So if the field value was:

This is a <b>test</b> with "quotes" and 'apostrophes' & ampersands

The output would be:

This is a &lt;b&gt;test&lt;/b&gt; with &quot;quotes&quot; and &#39;apostrophes&#39; &amp; ampersands

This prevents the text from being interpreted as actual HTML.

You’ll want to escape ACF values anywhere they’re output, like:

  • In the_content()
  • the_excerpt()
  • the_title()
  • Widgets (text, HTML, etc.)
  • The Loop
  • Comments
  • etc.

So your code may look something like this:

the_content( esc_html( get_field('my_content') ) ); 
[php]

or

[php]
echo esc_html( get_field('my_text') ); 


in various places throughout your theme and plugins.

 

Other Methods for Sanitizing ACF HTML

One way to fix this warning is by sanitizing ACF fields that contain HTML. There are a few methods for sanitizing HTML in WordPress and with ACF.

esc_attr()

The esc_attr() function escapes HTML attribute values. Use this when outputting ACF field values in HTML attributes. For example:

echo '&amp;amp;amp;amp;lt;a href="' . esc_attr($field_value) . '"&amp;amp;amp;amp;gt;Link&amp;amp;amp;amp;lt;/a&amp;amp;amp;amp;gt;';

This will escape the $field_value, making it safe to use in the href attribute.

esc_html()

The esc_html() function escapes HTML for output in the HTML body. Use this when outputting ACF field values that will be displayed as raw HTML. For example:

echo esc_html($field_value);

This will escape the $field_value, making it safe to echo as HTML.

wp_kses_post()

The wp_kses_post() function strips out any invalid HTML and sanitizes the remaining HTML to ensure it’s safe for output. This is a more comprehensive sanitization method compared to esc_html(). Use this when allowing users to enter custom HTML in an ACF field.For example:

echo wp_kses_post($field_value);

This will sanitize the $field_value and strip out any unsafe HTML before outputting.

ACF Stripsafe

The Stripsafe ACF add-on allows you to configure allowed HTML tags, attributes and protocols on a per-field basis. This gives you granular control over HTML sanitization for ACF fields.

Should I sanitize ACF values on save or output?

It is best practice to sanitize ACF field values on output rather than save. This allows you to sanitize values for different contexts, and allows HTML/scripts in fields that are safely output in certain contexts.

What sanitization method should I use?

It depends on your needs. Use esc_attr() for attributes, esc_html() for basic HTML, wp_kses_post() for more comprehensive sanitization, and ACF Stripsafe for granular control.

When You Should Not Escape ACF HTML Output

Sometimes you’ll want ACF to output HTML instead of escaping it. For example, if you’re using ACF to build a post content editor with a rich text editor field, you’ll want the field to output HTML to properly format the content.

To tell ACF not to escape a field’s output, you can add esc_html => false to the field’s arguments:

$args = array(
    'label' =&amp;amp;amp;gt; 'Content',
    'name' =&amp;amp;amp;gt; 'content',
    'type' =&amp;amp;amp;gt; 'wysiwyg',
    'toolbar' =&amp;amp;amp;gt; 'full',
    'esc_html' =&amp;amp;amp;gt; false
);

acf_add_local_field_group(array(
    'key' =&amp;amp;amp;gt; 'group_1234',
    'title' =&amp;amp;amp;gt; 'Content',
    'fields' =&amp;amp;amp;gt; array($args)
));

Now the content field will output raw HTML which WordPress will properly format on the frontend.

You’ll also want to do this for any field where you intend to have HTML in the value, such as:

  • Textarea fields
  • Code fields
  • Gallery fields
  • Etc.

Any field where you’re allowing editors to add custom HTML, you’ll need to set esc_html => false. Otherwise, ACF will escape the HTML to prevent XSS vulnerabilities.

Escaping Unsafe HTML Rendered by ACF The_field()

ACF PRO recently started warning you that “ACF will soon escape unsafe HTML that is rendered by the_field()”. What does this mean and how can you fix it?

When ACF renders a field using the_field(), it outputs the value without escaping it. This means if the value contains HTML, it will be executed. While this is useful in some cases, it can also pose a security risk. To fix this, ACF PRO will automatically escape values to prevent unwanted HTML execution.

To fix this warning and opt-in to escaping values, you have two options:

  1. Add esc_html() when echoing the_field()
echo esc_html( the_field('some_field') );
  1. Add ‘escape_output’ => true when registering the field
acf_add_local_field( array(
'key' =&amp;gt; 'some_field',
'name' =&amp;gt; 'Some Field',
'type' =&amp;gt; 'text',
'escape_output' =&amp;gt; true
) );

This will tell ACF to automatically escape the value for this field when using the_field().

FAQ

  • I have an HTML form where users can enter content. Should I sanitize that input?

    Yes, always sanitize any HTML input before displaying it. Use a library like HTML Purifier to remove unsafe tags and attributes.

  • What's the difference between sanitizing and escaping HTML?

    Sanitizing HTML filters out unsafe elements, attributes, and code. Escaping HTML converts special characters like < and > into HTML entities (< and >) which prevents the browser from executing any code. For security, you should sanitize first, then escape.
  • How can I prevent XSS attacks?

    To prevent XSS attacks, follow these best practices:

    • Sanitize all user input, especially HTML, JavaScript, CSS, and URL input.
    • Use a library like HTML Purifier, DOMPurify or bleach to sanitize HTML.
    • Escape all output, including data from databases, with htmlspecialchars() or esc_html().
    • Use httponly, secure, and samesite cookies to prevent cookie theft.
  • Do I need to sanitize on the front-end and back-end?

    Yes, it's best practice to sanitize data on both sides. Sanitize when saving data to the database (back-end) and also when outputting data to the front-end. Without sanitizing, malicious users could input JavaScript or other code into your ACF fields and have it execute on your site. This is a major security risk known as an XSS (cross-site-scripting) attack. You only need to sanitize string data that will be output to the page. Numbers, dates, file uploads, etc. do not need to be sanitized.

  • How do I fix fields that have already been created?

    Unfortunately, you'll need to manually edit any existing ACF fields and add the necessary esc_html() and esc_attr() calls. Any new fields you create will need to have sanitization added right away.

    To fix the "ACF PRO Will Soon Escape Unsafe HTML" warning and lock down the security of your site's data, be sure to sanitize all ACF output using esc_html() and esc_attr(). Your users and server will thank you!

  • What if I don't fix this warning?

    If left unfixed, upcoming versions of ACF PRO will automatically escape unsafe HTML in your field values to prevent security issues. Some formatting loss may occur, so it's best to manually clean up or enable escaping on the fields. ACF PRO is improving security by escaping unsafe HTML output. This warning gives you a chance to opt-in to the new escaping behavior. ACF PRO will require escaping or sanitizing field values in a future update. This warning gives you time to make the necessary updates to your templates to avoid issues when that change occurs.

  • What about when using ACF in widgets?

    Yes, you'll want to escape ACF values in widgets as well before outputting them. Simply call esc_html() on the field value same as anywhere else.

  • Will enabling "Escape HTML" affect my field values?

    Enabling this setting will convert any unsafe HTML in your field values to plain text. Some formatting may be lost, but it helps prevent vulnerabilities.

Codeable service can fix this for you!

Find Developer

Reach out to the Codeable experts for help. Their WordPress developers can fully audit your site and ACF PRO integration to fix any issues causing warnings.

There are a few key benefits to having Codeable audit your site:

• Comprehensive review – We will review all instances of ACF on your site, including fields, locations, and how ACF is integrated with your theme.

• Technical expertise – Our developers are ACF PRO experts and can identify issues that may be causing the unsafe HTML warning.

• Custom fixes – We will provide recommendations and implement any custom code fixes needed to resolve the warning and make your ACF integration safe and secure.

• Future-proofing – After fixing current issues, we can recommend best practices to implement going forward to avoid similar errors.

• Peace of mind – You’ll have confidence that your ACF PRO integration is running smoothly and not exposing your site to risk.

If you’d like a free consultation to discuss an ACF PRO audit for your site, feel free to reach out. We can review your issues, provide a free quote, and develop a customized plan to resolve any ACF or WordPress integration issues.

How to Automatically Change WooCommerce Product Order Status from Processing to Completed status

Running a successful WooCommerce store involves efficient order management. One way to streamline this process is by automatically switching the order status from “Processing” to “Completed.” In this comprehensive guide, we’ll explore two methods to achieve this: using a custom function and utilizing a plugin.

Method 1: Using a Custom Function

Step 1: Access Your Theme’s functions.php File

  1. Log in to Your WordPress Dashboard: Begin by accessing your WordPress admin dashboard.
  2. Navigate to “Appearance”: Click on “Appearance” in the left-hand menu.
  3. Select “Theme Editor”: Choose “Theme Editor” to access your theme’s files.
  4. Locate and Open “functions.php”: In the list of theme files on the right-hand side, find and select the “functions.php” file.

Step 2: Insert the Custom Function

Now, let’s insert the custom function that automates the order status change:

function auto_complete_orders() {
    // Retrieve all orders with "Processing" status
    $processing_orders = wc_get_orders( array(
        'status' => 'processing',
        'limit' => -1,
     ) );

     // Loop through each "Processing" order and change its status to "Completed"
     foreach ( $processing_orders as $order ) {
        $order->update_status( 'completed' );
     }
}
add_action( 'woocommerce_order_status_processing', 'auto_complete_orders' );
<pre>

 

This code defines a function called auto_complete_orders that triggers when an order’s status changes to “Processing.” It then automatically changes the order status to “Completed.”

Method 2: Using a Plugin

Step 1: Install and Activate a Plugin

For those who prefer a user-friendly approach without coding, plugins offer a convenient solution. Follow these steps:

  1. Login to Your WordPress Admin Dashboard: Access your WordPress admin dashboard.
  2. Visit the “Plugins” Section: Navigate to the “Plugins” section in the left-hand menu.
  3. Click “Add New”: Select “Add New” to search for and install a suitable plugin.
  4. Search and Install: In the search bar, type the name of a plugin like “WooCommerce Auto-Complete Orders.” Once found, click “Install” and then “Activate.”

Step 2: Configure Plugin Settings

After activating the plugin, you can configure its settings:

  • Specify Order Status: Typically, these plugins allow you to specify the order status that triggers the automatic change to “Completed.” Customize these settings according to your requirements.

Automatically Change WooCommerce Product Order Status from Processing to Completed status

By automating the transition from “Processing” to “Completed” order status in WooCommerce, you can simplify your order management processes, reduce manual workload, and enhance the overall customer experience. Whether you choose the custom function or plugin method, thorough testing on a staging site is essential to ensure seamless functionality and avoid conflicts with other plugins or themes on your live website.