子主题的目录结构
子主题也是一个主题,也跟其他主题一样,放在 wp-content/themes 目录下面的文件夹中,文件夹的名称可以随便定义,为了形象一点,在示例中,我们可以新建 twentytwelve-child 这样一个文件夹存放子主题。这样的话,我们的 themes 文件夹中,至少有两个文件夹:twentytwelve、twentytwelve-child ,因为子主题要基于父主题,所以主题目录肯定要有父主题。
在子主题中,一般有下面几个文件:
style.css (这个必须有)
functions.php (这个可以有)
其他模板文件 (这个可以有)
其他文件 (这个可以有)
style.css 是必须的
这是构建子主题中唯一必须有的文件,因为 WordPress 根据主题中的 style.css 头部信息来获取主题信息。特别是子主题,除了像一般主题一样添加头部信息之外,还需要添加父主题的名称,这样 WordPress 才能获取父主题的资源文件。
style.css 头部信息
/* Theme Name: Twenty Twelve Child Theme URI: http://example.com/ Description: Child theme for the Twenty Twelve theme Author: Your name here Author URI: http://example.com/about/ Template: twentytwelve Version: 0.1.0 */
functions.php
//B2子主题目录url
define( 'B2_CHILD_URI', get_stylesheet_directory_uri() );
//加载父级样式(一般不用修改)
add_action( 'wp_enqueue_scripts', 'parent_theme_enqueue_styles',9 );
function parent_theme_enqueue_styles() {
//加载父主题样式文件
wp_enqueue_style( 'parent-style-main', get_template_directory_uri() . '/style.css',array() , B2_VERSION, 'all' );
wp_enqueue_style( 'parent-style', get_template_directory_uri().'/Assets/fontend/style.css',array() , B2_VERSION, 'all');
}
//加载子主题样式
add_action( 'wp_enqueue_scripts', 'child_theme_enqueue_styles',99 );
function child_theme_enqueue_styles() {
//禁用当前子主题默认加载项
wp_dequeue_style( 'b2-style-main' );
wp_dequeue_style( 'b2-style' );
//加载子主题样式文件,使它在所有样式之后
wp_enqueue_style( 'child-style', B2_CHILD_URI.'/style.css' , array() , B2_VERSION, 'all');
//加载子主题JS文件
wp_enqueue_script( 'b2-child', B2_CHILD_URI.'/child.js', array(), B2_VERSION , true );
}