在WordPress中链接外部JS和CSS文件

dav*_*lee 3 javascript css wordpress

我是Wordpress框架的新手.我可以知道如何将外部CSS和JS文件链接到我的Wordpress页面吗?我创建了一个新页面,但我想将CSS和JS文件链接到它.

是创建新模板还是插件解决方案?我对此完全陌生.

小智 8

我知道这个帖子有点过时但也许其他人可能觉得它很有用.

包含外部CSS和JS文件的正确方法是使用wp_enqueue_style method和使用esc_url_rawsource参数.

例如,要将ta google字体包含在您的主题中,您需要执行以下操作:

wp_enqueue_style( 'twentytwelve-googlefonts', esc_url_raw( 'http://fonts.googleapis.com/css?family=Titillium+Web:600,300,200' ), array(), null );
Run Code Online (Sandbox Code Playgroud)


小智 5

取决于您是否要有条件地添加CSS或JS。如果希望它们包含在所有文件中,只需使用主题文件夹的functions.php页面,然后添加:

            function your_scripts() {
                    wp_register_script('yourscriptname', '/PATH/TO/YOUR/SCRIPT.js', false);
                    // This registers your script with a name so you can call it to enqueue it
                    wp_enqueue_script( 'yourscriptname' );
                    // enqueuing your script ensures it will be inserted in the propoer place in the header section
            }
            add_action('wp_enqueue_scripts', 'your_scripts');
            // This hook executes the enqueuing of your script at the proper moment.
Run Code Online (Sandbox Code Playgroud)

对于样式表,请按照以下方式进行:

            function your_css() {
                wp_register_style( 'nameofyourCSSsheet', '/PATH/TO/YOUR/STYLESHEET.css' );
                wp_enqueue_style( 'nameofyourCSSsheet' );
            }
            add_action( 'wp_enqueue_scripts', 'your_css' );
            // same hook is used to enqueue CSS sheets
Run Code Online (Sandbox Code Playgroud)