简体   繁体   English

删除联系表格 7 CSS 和 JS 除非页面中使用联系表格 7 短代码

[英]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.我只想在该页面中使用短代码时显示 css 和 javascript。 If the short code not present in the wordpress page then the js and css of contact form should not be shown.如果 wordpress 页面中没有短代码,则不应显示联系表单的 js 和 css。 For that what i have done is i have pasted the following code in my active themes function.php file.为此,我已将以下代码粘贴到我的活动主题 function.php 文件中。

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.上面的代码完全去掉了contact form 7插件的js和css。 What i need is if contact form 7 shortcode is pasted then both should be shown.我需要的是,如果粘贴了联系表格 7 短代码,那么两者都应该显示。

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.如果没有简码,联系表单的 css 和 js 将被删除,如果有简码 css 和 js 将被添加。

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');

You use below code.You can add your pages Id in this code.您使用以下代码。您可以在此代码中添加您的页面 ID。

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 参考

I needed the other version that corresponds widgets and shortcodes in theme file.我需要与主题文件中的小部件和短代码相对应的其他版本。

add_filter( 'wpcf7_load_css', '__return_false' );

add_filter( 'wpcf7_load_js', '__return_false' );

remove_action( 'wp_enqueue_scripts','wpcf7_recaptcha_enqueue_scripts', 20 );

add_filter('pre_do_shortcode_tag', 'enqueue_wpcf7_css_js_as_needed', 10, 2 );
function enqueue_wpcf7_css_js_as_needed ( $output, $shortcode ) {
    if ( 'contact-form-7' == $shortcode ) {
        wpcf7_recaptcha_enqueue_scripts();
        wpcf7_enqueue_scripts();
        wpcf7_enqueue_styles();
    }
    return $output;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM