我正在尝试将 styles.css 样式表包含在我正在尝试开发的 WordPress 主题中(我的第一个主题)。问题:如何将其纳入其中?我知道将以下代码放入 header.php 文件中可以正常工作:
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>">
但是我宁愿通过functions.php 包含它,如下所示:
<?php
function firstTheme_style(){
wp_enqueue_style( 'core', 'style.css', false );
}
add_action('wp_enqueue_scripts', 'firstTheme_style');
?>
但这根本不起作用(当我从 header.phps 'head' 中删除该行时,我的样式看不到?
以下方法包括
style.css
。
方法 - 1
// add in your header.php
<link rel="stylesheet" href="<?php echo get_stylesheet_uri(); ?>">
方法 - 2
// load css into the website's front-end
function mytheme_enqueue_style() {
wp_enqueue_style( 'mytheme-style', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_style' );
方法 - 3
// Add this code in your functions.php
function add_stylesheet_to_head() {
echo "<link href='".get_stylesheet_uri()."' rel='stylesheet' type='text/css'>";
}
add_action( 'wp_head', 'add_stylesheet_to_head' );
最佳实践是在
functions.php
中创建自定义函数
function custom_function(){}
之后尝试使用此WordPress功能
wp_enqueue_style
来调用CSS文件安全性
function custom_function(){
wp_enqueue_style ('any-name',get_template_directory_uri().'/css/style.css');}
并添加
add_action
功能
add_action( 'wp_enqueue_scripts', 'custom_function' );
包含 styles.css 文件的最佳方法是在主题中添加以下代码
functions.php
:
function themename_enqueue_style() {
wp_enqueue_style( 'themename-style', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'themename_enqueue_style' );
只需添加一些细节,也许会对某人有所帮助。如果您打算在现有主题的functions.php中包含style.css,请检查它是否使用命名空间。例如,在我必须编辑的 Raft 主题中,functions.php 顶部有一行:
namespace Raft;
本例代码
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_style' );
将生成错误“致命错误:未捕获的类型错误:call_user_func_array():参数#1 ($callback) 必须是有效的回调”。定义回调的命名空间:
add_action( 'wp_enqueue_scripts', 'NamespaceValue\mytheme_enqueue_style' );
并且有效。