Load Contact Form 7 Scripts & Styles Only When Needed

[ad_1]

Without any doubts, the Contact Form 7 is one of the best WordPress plugin for creating and adding contact forms to your website. The plugin is very easy to set up and use. The only issue with this plugin is that it includes required JavaScript and CSS file on every page regardless of the page may or may not have form generated by this plugin. This makes your site load slower than necessary because browser has to make 3 HTTP requests extra on each page load. The styling and JavaScript for a contact form is usually only needed on the page where the actual contact form is.

The good news is that there is an easy solution to this little problem. In this article we will show you how to load the scripts and styles of Contact Form 7 plugin only on the pages that need them.

Add the following WordPress snippet to your theme’s functions.php file to load the scripts and styles only on pages that have a contact form. This snippet checks if the current post or page contains the contact-form-7 shortcode, and if it does not then it will tell WordPress not to load the Contact Form 7 scripts and styles.

// load contact form 7 scripts & styles only when needed
function wcs_cf7_scripts_conditional_load() {
  $load_scripts = false;
  if ( is_singular() ) {
    $post = get_post();
    if( has_shortcode( $post->post_content, 'contact-form-7' ) ) {
        $load_scripts = true;
    }
  }
  if ( ! $load_scripts ) {
    wp_dequeue_script( 'contact-form-7' );
    wp_dequeue_style( 'contact-form-7' );
  }
}
add_action( 'wp_enqueue_scripts', 'wcs_cf7_scripts_conditional_load', 99 );  

source

[ad_2]

Leave a Reply

Random Post Selection ::

Recent Posts

Unlock Unlimited Downloads