thematic 子主题引用JS的方法

来源:互联网 发布:淘宝店铺搬家到微店 编辑:程序博客网 时间:2024/05/16 11:23

在wordpress主题框架的世界里,基于主题框架开发的主题被称之为childtheme,翻译成中文为“子主题”,这个说法很别扭,但是没有更好的中文称呼了。

利用thematic进行wordpress的主题开发的确很便捷,例如我们要引用一个JS脚本。

首先我们看一下thematic框架是如何引用JS脚本文件的,打开header-extensions.php,这个文件位于wp-content\themes\thematic\library\extensions\目录下,打开这个文件后找到如下代码

if (function_exists('childtheme_override_head_scripts'))  {    function thematic_head_scripts() {    childtheme_override_head_scripts();    }} else {    function thematic_head_scripts() {    $scriptdir_start = "\t";    $scriptdir_start .= '<script type="text/javascript" src="';    $scriptdir_start .= get_bloginfo('template_directory');    $scriptdir_start .= '/library/scripts/';        $scriptdir_end = '"></script>';        $scripts = "\n";    $scripts .= $scriptdir_start . 'hoverIntent.js' . $scriptdir_end . "\n";    $scripts .= $scriptdir_start . 'superfish.js' . $scriptdir_end . "\n";    $scripts .= $scriptdir_start . 'supersubs.js' . $scriptdir_end . "\n";    $dropdown_options = $scriptdir_start . 'thematic-dropdowns.js' . $scriptdir_end . "\n";        $scripts = $scripts . apply_filters('thematic_dropdown_options', $dropdown_options);    $scripts .= "\n";    $scripts .= "\t";    $scripts .= '<script type="text/javascript">' . "\n";    $scripts .= "\t\t" . '/*<![CDATA[*/' . "\n";    $scripts .= "\t\t" . 'jQuery.noConflict();' . "\n";    $scripts .= "\t\t" . '/*]]>*/' . "\n";    $scripts .= "\t";    $scripts .= '</script>' . "\n";    // Print filtered scripts    print apply_filters('thematic_head_scripts', $scripts);}}

 

看到这里我们就可以领略到thematic的便捷之处了,在这里先是用IF语句判断childtheme_override_head_scripts()这个函数是否存在,如果存在即实行这个函数,否则将运行thematic默认的函数:thematic_head_scripts(),既然我们是要引用框架外的JS脚本,那么我们在子主题目录中的functions.php中创建一个childtheme_override_head_scripts()即可,具体的实现代码如下:

function childtheme_override_head_scripts(){$scriptdir_start = "\t";    $scriptdir_start .= '<script type="text/javascript" src="';    $scriptdir_start .= get_bloginfo('stylesheet_directory');//如果用bloginfo('template_directory')这个参数来获取路径,那么取得的将是thematic框架所在目录的路径,用get_bloginfo('stylesheet_directory')得到的是我们子主题的路径,我们强烈推荐这种做法!    $scriptdir_start .= '/';        $scriptdir_end = '"></script>';        $scripts = "\n";    $scripts .= $scriptdir_start . 'main.js' . $scriptdir_end . "\n";        $scripts = $scripts . apply_filters('thematic_dropdown_options', $dropdown_options);    // Print filtered scripts    print apply_filters('thematic_head_scripts', $scripts);}


在thematic官方论坛上还给出了另一种引用JS脚本的方法:

<?php function childtheme_scripts() {?><?php echo "\n\t" ?><script type="text/javascript" charset="utf-8" src="<?php bloginfo('template_directory'); ?>/js/coda-slider.js"></script><?php echo "\n" ?><?php }add_action('wp_head', 'childtheme_scripts'); ?>


第一种方法会导致thematic框架默认引入JS脚本的函数失效,如果不希望thematic默认的引入JS脚本的函数失效,请用第二种方法引入自定义JS脚本。

 

无论使用以上两种方法中的哪一种,都要注意定义脚本存放的路径。


 

原创粉丝点击