Add Snippet To Project
Are you looking to have Contact Form 7 enabled on specific pages of your WordPress website and deactivate it on all other pages? If so, you’ve come to the right place. In this article, we will guide you through the process of enabling Contact Form 7 on specified pages only, while using wp_deregister_script to deactivate it on the rest of your website. By following these steps, you’ll have full control over where your contact form is displayed, allowing you to streamline your website’s user experience. Let’s dive in and get started!
function wpturbo_enable_contact_form_7() {
if ( is_page( array( 'contact', 'about' ) ) ) {
wp_enqueue_script( 'contact-form-7' );
} else {
wp_deregister_script( 'contact-form-7' );
}
}
add_action( 'wp_enqueue_scripts', 'wpturbo_enable_contact_form_7' );
The wpturbo_enable_contact_form_7()
function serves the purpose of enabling the Contact Form 7 script on specified pages only. If the current page is either the "contact" or "about" page, the function will enqueue the Contact Form 7 script using the wp_enqueue_script()
function. Else, it will deregister the Contact Form 7 script using the wp_deregister_script()
function.
To start, we define the function wpturbo_enable_contact_form_7()
. Within this function, we use the is_page()
function with an array of page slugs as the parameter. In this case, the array contains the slugs of the "contact" and "about" pages.
The is_page()
function checks if the current page is one of the specified pages. If it evaluates to true, meaning the current page matches one of the specified pages, it proceeds with enqueuing the Contact Form 7 script using wp_enqueue_script()
. This ensures that the necessary JavaScript files for Contact Form 7 are loaded.
if ( is_page( array( 'contact', 'about' ) ) ) {
wp_enqueue_script( 'contact-form-7' );
}
On the other hand, if the current page does not match any of the specified pages, the else
block is executed. Inside the else
block, the wp_deregister_script()
function is used to deregister the Contact Form 7 script. This prevents the script from being loaded on pages where it is not needed, thereby improving performance by reducing unnecessary script loading.
else {
wp_deregister_script( 'contact-form-7' );
}
Finally, we hook the wpturbo_enable_contact_form_7()
function to the wp_enqueue_scripts
action using the add_action()
function. This ensures that the function is executed when the frontend scripts are being enqueued.
add_action( 'wp_enqueue_scripts', 'wpturbo_enable_contact_form_7' );
By using this code snippet, you can enable the Contact Form 7 script on specific pages where you need it and deregister it on other pages to improve the performance of your website.