【问题标题】:How do I properly use an action hook to enqueue my CSS file in WordPress through using functions.php?如何通过使用functions.php正确使用动作挂钩将我的CSS文件排入WordPress中?
【发布时间】:2021-08-23 02:30:18
【问题描述】:

我一直试图让这段代码在我的子主题的functions.php 文件中工作,以便将我的自定义 CSS 文件正确地排入名为“仪表板”的模板文件/页面。据我了解,functions.php 文件是在主查询之前加载的,因此我使用了一个带有回调的操作挂钩,如下所示。但它似乎不起作用。我们将不胜感激。

functions.php

add_action('get_header', function() {
    if(is_page('dashboard')) {

        function enqueue_style() {
          wp_enqueue_style( 'dashboard-css', 'https://myurl.com/wp-content/themes/astra-child/css/dashboard.css', false ); 
        }

        add_action( 'wp_enqueue_scripts', 'enqueue_style' );
    }
});

dashboard.php

<?php /*Template Name: User Dashboard*/?>
<head> 

</head>
<body>
<p>this is my dashboard</p>
</body>

【问题讨论】:

    标签: php wordpress wordpress-theming


    【解决方案1】:

    functions.php 文件中尝试这样的代码。

    function enqueue_style() {
        global $wp_styles, $wp_scripts;
        $protocol = is_ssl() ? 'https' : 'http';
        if(is_page('dashboard')) {
             // Register 
             wp_register_style('dashboard-css', get_stylesheet_directory_uri() . '/css/dashboard.css');
             // Enqueue
             wp_enqueue_style('dashboard-css'); 
        }
    }
    add_action('wp_enqueue_scripts', 'enqueue_style');
    

    【讨论】:

    • 它也不好用。它可能与我正在使用的主题有关吗?是阿斯特拉。
    • 我还检查了 CSS 文件是否是使用 if 语句在模板文件中使用 wp_style_is('dashboard-css') 注册的,它是错误的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    相关资源
    最近更新 更多