WordPress只在文章页面加载指定JS/CSS

Kevin 杂记 829 次浏览 11条评论

对于某些特定功能JS或CSS文件,也许只是特定页面用到,不需要全站加载,这时可以按条件引入。话不多说,实现方法见下文(通过wp_enqueue_scripts函数加载文件,也是WordPress建议用法)

/**
 * Enqueue scripts and styles.
 */
function wp_load_scripts() {
    // 全站加载资源(演示文件引入方法)
    wp_enqueue_style( 'theme-style', get_theme_file_uri( '/assets/main.css' ), array(), null );
    wp_enqueue_script( 'theme-jquery', get_theme_file_uri( '/assets/main.js' ), array(), null );
    // 仅在“文章”和“页面”加载
    if ( is_single() || is_page() ) {
        wp_enqueue_script( 'post-jquery', get_theme_file_uri( '/assets/post.js' ), array(), null );
    }
    // 仅在指定“页面”加载(WP后台查看页面链接的ID参数)
    if ( is_page( ID ) ) {
        wp_enqueue_script( 'page-jquery', get_theme_file_uri( '/assets/page.js' ), array(), null );
    }
    // 仅在特定“页面模板”加载
    if( is_page() ) {
        global $wp_query;
        // 根据“页面模板”文件名匹配
        $page_template_name = get_post_meta( $wp_query->post->ID, '_wp_page_template', true );
        if($page_template_name == 'onecolumn-page.php'){
            wp_enqueue_script( 'page-jquery', get_theme_file_uri( '/assets/page.js' ), array(), null );		
        }
    }
}
add_action( 'wp_enqueue_scripts', 'wp_load_scripts' );

将代码放入functions.php文件生效。如有需要,你也可以按例子添加其它判断条件。

评论列表

  1. #1

    Keep up thee great piece of work, I read few osts on this website
    and I thin that your site is very interesting andd has got sets
    of wonderful information.

    Here is my web page :: Review Mfm5 Forex Robot

  2. #2

    It’s perfect tume to make a few plans for the long run and it’s time to be happy.
    I have read this put up and if I could I desire to suggest you few
    interesting things or advice. Maybe you can write subsequent articles relating to this article.
    I wis to read even more things about it!

    Also vist my web page :: mfm5 myfxbook

  3. #3

    normal dapoxetine dose https://salemeds24.wixsite.com/dapoxetine

  4. #4

    hydroxychloroquine for rheumatoid arthritis https://hydroxychloroquine.webbfenix.com/

  5. #5

    bimatoprost cvs https://carepro1st.com/

  6. #6

    liquid tadalafil for sale http://www.lm360.us/

  7. #7

    clomiphene success rate https://salemeds24.wixsite.com/clomid

  8. #8

    stromectol 3 mg price https://ivermectin.webbfenix.com/

  9. #9

    how to maximize vidalista effects https://vidalista.mlsmalta.com/

  10. #10

    hydroxychloroquine by state https://hydroxychloroquine.mlsmalta.com/

  11. #11

    how much is sildenafil http://droga5.net/

发表评论

电邮地址用于 Gravatar 头像显示,不会被公开可见。