wordpress - 为什么使用 wp_enqueue_style 比 WordPress 中的链接标签更好?

标签 wordpress

我是 WordPress 开发的新手。我读到最好在 functions.php 文件中使用 wp_enqueue_styledo_action 而不是像不使用 WordPress 时那样直接链接 CSS 文件.

为什么这是最佳做法?它有什么优势?

最佳答案

如果您已激活子主题,则使用 get_template_directory_uri() 函数。

如果您已激活父主题,则使用 get_stylesheet_directory_uri() 函数。


get_template_directory_uri将始终引用 Assets 的父主题文件夹。

get_stylesheet_directory_uri将引用 Assets 的“当前”主题文件夹(可以是父项或子项,具体取决于调用位置)。

Child theme example:

wp_enqueue_style( 'my_child_styles', get_stylesheet_directory_uri().'/style.css' );

Parent theme Example

wp_enqueue_style( 'my_parent_styles', get_template_directory_uri().'/style.css' );

方法一

// load css into the website's front-end
function mytheme_enqueue_style() {
    wp_enqueue_style( 'mytheme-style', get_stylesheet_directory_uri().'/style.css' ); 
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_style' );

方法二

// Add this code in your functions.php
function add_stylesheet_to_head() {
      echo "<link href='".get_stylesheet_directory_uri()."/style.css' rel='stylesheet' type='text/css'>";
}

add_action( 'wp_head', 'add_stylesheet_to_head' );

关于wordpress - 为什么使用 wp_enqueue_style 比 WordPress 中的链接标签更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41825241/

相关文章:

wordpress - 在 wordpress 中特定天数后自动删除已发布的帖子

php - wp_posts.id 值超过 9 位会导致帖子和权限问题

wordpress - jQuery 就绪功能在 WordPress 中不起作用

wordpress - 将跨度添加到存档帖子计数

html - 使用 Bootstrap 将事件类动态添加到 Wordpress 中的自定义菜单

wordpress - Wordpress未在Docker端口8000上运行

html - 无法直接设置 CSS 样式或样式 HTML 属性

php - 如何通过自定义帖子类型、自定义元框、类别、评论、作者列表分别从 WordPress 站点检索 Android 应用程序的 JSON 数据

wordpress - 自定义 Woocommerce 客户帐户页面

jquery - markItUp for Wordpress 小部件