您好 我需要一些帮助来为我的页面模板创建自定义css文件。 关于这个问题有很多主题,但我阅读的每个帖子都会得到更多的信息,而且更加困惑。
我为二十四个主题创建了一个子主题,并添加了一个页面模板。如何将自定义css添加到此模板。我发现了 这段代码添加到了child-theme的functions.php中,用我的css选择了合适的类。但是我如何以及在哪里上课?我读到我必须将该类添加到header.php中的body标签,但我不确定。这是正确的方法吗?
if (is_page_template( 'mytemplate.php' )){
$classes[] = 'myclass';
}
答案 0 :(得分:18)
使用is_page_template()
条件来有选择地加载CSS。
在下面的函数中,我们挂钩wp_enqueue_scripts
并检查我们是否在自定义页面模板上以确定是否加载其他CSS。
如果结果为true,我们将从主题中的page-template.css
文件夹中加载标题为css/
的CSS文件。更新路径以加载正确的文件。
function wpse_enqueue_page_template_styles() {
if ( is_page_template( 'mytemplate.php' ) ) {
wp_enqueue_style( 'page-template', get_template_directory_uri() . '/css/page-template.css' );
}
}
add_action( 'wp_enqueue_scripts', 'wpse_enqueue_page_template_styles' );
答案 1 :(得分:11)
这个解决方案怎么样?
<?php
function mypage_head() {
echo '<link rel="stylesheet" type="text/css" href="'.get_bloginfo('stylesheet_directory').'/includes/mypage.css">'."\n"
}
add_action('wp_head', 'mypage_head');
?>
<?php get_header(); ?>
您可以使用wp_head
hook将自定义内容(Javascript,CSS ..)添加到自定义模板中。我认为这种方式更好,因为所有更改都会包含在您的模板文件中,因此您不必在其他地方办理登机手续。
我从http://scratch99.com/wordpress/development/custom-page-template-external-css-file/获得此解决方案。
答案 2 :(得分:0)
这个怎么样?
function my_custom_styles() {
wp_register_style( 'custom-styles', get_template_directory_uri().'/lib/styles/custom-styles.css' ) );
if ( is_home ) {
wp_enqueue_style( 'custom-styles' );
}
}
add_action( 'wp_enqueue_scripts', 'my_custom_styles' );
我从这里测试了所有三个答案;而且他们都很棒。有人知道哪一个更快更好吗?更好?