Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Contact Form 7 CSS and JS Unless Contact form 7 shortcode is used in the page

I want to show the css and javascript only when the shortcode is used in that page. If the short code not present in the wordpress page then the js and css of contact form should not be shown. For that what i have done is i have pasted the following code in my active themes function.php file.

add_filter( 'wpcf7_load_js', '__return_false' );
add_filter( 'wpcf7_load_css', '__return_false' );

The above code totally removes the js and css of contact form 7 plugin. What i need is if contact form 7 shortcode is pasted then both should be shown.

like image 726
James Paul Avatar asked Feb 22 '18 09:02

James Paul


2 Answers

Here is the answer for your question. If there is not shortcode the css and js of contact form will be removed and if there is shortcode css and js will be added.

function rjs_lwp_contactform_css_js() {
    global $post;
    if( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'contact-form-7') ) {
        wp_enqueue_script('contact-form-7');
         wp_enqueue_style('contact-form-7');

    }else{
        wp_dequeue_script( 'contact-form-7' );
        wp_dequeue_style( 'contact-form-7' );
    }
}
add_action( 'wp_enqueue_scripts', 'rjs_lwp_contactform_css_js');
like image 55
J. Shabu Avatar answered Sep 21 '22 17:09

J. Shabu


You use below code.You can add your pages Id in this code.

function dvk_dequeue_scripts() {

    $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', 'dvk_dequeue_scripts', 99 );

Reference

like image 20
developerme Avatar answered Sep 21 '22 17:09

developerme