Enable Contact Form 7 to Work with Disable WP REST API
My free WordPress plugin, Disable WP REST API, disables the REST API for all users who are not logged in to WordPress. So if you’re using a plugin such as Contact Form 7 that requires the REST API, it’s not going to work if Disable WP REST API is active on site. But there is a way to make it work. This quick tutorial explains how to set it up in two steps.
Step 1: Get the REST URIs
Open your browser’s console and visit your contact form 7. The goal here is to look at any 401 errors and get the associated URIs/paths. For example, using Firefox console while visiting and submitting the contact form shows several 401 (Unauthorized) URIs. Here is a screenshot to give you a better idea:
To illustrate with a concrete example, here are the related REST URIs (end points) that were getting denied due to the Disable WP REST API plugin.
/wp-json/contact-form-7/v1/contact-forms/1757/refill
/wp-json/contact-form-7/v1/contact-forms/1757/feedback
/wp-json/contact-form-7/v1/contact-forms/1757/feedback/schema
Step 2: Add REST URIs to custom code
Once you have all the REST URIs required by Contact Form 7, the next step is to add them to a whitelist, so they always will have access, even when the user is not logged in. So as it should be, any random visitor can use your contact form. To do it, add the following custom code via theme functions or simple plugin.
function disable_wp_rest_api_server_var_custom($var) {
return array(
'/wp-json/contact-form-7/v1/contact-forms/1757/refill',
'/wp-json/contact-form-7/v1/contact-forms/1757/refill/',
'/wp-json/contact-form-7/v1/contact-forms/1757/feedback',
'/wp-json/contact-form-7/v1/contact-forms/1757/feedback/',
'/wp-json/contact-form-7/v1/contact-forms/1757/feedback/schema',
'/wp-json/contact-form-7/v1/contact-forms/1757/feedback/schema/'
);
}
add_filter('disable_wp_rest_api_server_var', 'disable_wp_rest_api_server_var_custom');
Notice that, in addition to the 3 REST URIs discovered in Step 1. We also add their “slashed” versions. So we have /.../schema
and /.../schema/
(note the trailing slash). Covering both cases helps to ensure smooth operation and happy visitors :)
That’s all there is to it. Once the above code is added to your site, Contact Form 7 will work even when Disable WP REST API is active. It’s important to understand that this code will enable any/all visitors and bots to access the specified REST URIs (end points). Which is fine because they’re meant to be public in the first place.
