如何在特定的WordPress块模板上加入CSS文件?

发布于 2025-02-06 14:03:59 字数 654 浏览 4 评论 0 原文

情况:我正在使用WordPress开发一个主题'new block主题paradigm 。我想为使用我的 templates/foo.html 模板的任何页面添加 foo.css

我尝试的是:我有此功能进行调试。

function foo_enqueue() {
    echo '<pre>';
    print_r(
        get_page_template_slug(get_the_ID())
    );
    echo '</pre>';
}
add_action( 'wp_enqueue_scripts', 'foo_enqueue' );

使用 get_page_template_slug 函数的普通WordPress方法不适用于块主题模板。 get_page_template_slug 仅与传统的基于PHP的页面模板一起使用。

我设置了该调试功能,以查看它将返回的页面模板。它什么都没有。

Situation: I am developing a theme using Wordpress' new Block Theme paradigm. I would like to enqueue foo.css for any pages that are using my templates/foo.html template.

What I have tried: I have this function for debugging.

function foo_enqueue() {
    echo '<pre>';
    print_r(
        get_page_template_slug(get_the_ID())
    );
    echo '</pre>';
}
add_action( 'wp_enqueue_scripts', 'foo_enqueue' );

The normal Wordpress way of using the get_page_template_slug function does not work with Block Theme templates. get_page_template_slug only works with traditional PHP based page templates.

I have that debugging function set up to see what page template it would return. It returns nothing.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没有心的人 2025-02-13 14:03:59

要在有条件的模板/foo.html 的有条件地制定样式表中,请在基于块的主题中使用 get_post_meta(),使用键 _wp_page_template ,eg:

functions.php

// Register "foo" CSS to use when needed later
function register_foo_style() {
    wp_register_style( 'foo-template-css', get_template_directory_uri(). '/foo.css' );
}
add_action( 'init', 'register_foo_style' );

// Enqueue "foo" CSS only if the current post/page uses "foo" template
function foo_enqueue() {
    if ( get_post_meta( get_the_ID(), '_wp_page_template', true ) == "foo" ) {
        wp_enqueue_style( 'foo-template-css' );
    }
}
add_action( 'wp_enqueue_scripts', 'foo_enqueue' );

ref:ref:ref:ref:https://developer.wordpress.org/reference/functions/get_page_template_slug/#more-信息

To conditionally enqueue a stylesheet only for templates/foo.html in a block-based theme, check the name of the currently applied template with get_post_meta(), using the key _wp_page_template, eg:

functions.php

// Register "foo" CSS to use when needed later
function register_foo_style() {
    wp_register_style( 'foo-template-css', get_template_directory_uri(). '/foo.css' );
}
add_action( 'init', 'register_foo_style' );

// Enqueue "foo" CSS only if the current post/page uses "foo" template
function foo_enqueue() {
    if ( get_post_meta( get_the_ID(), '_wp_page_template', true ) == "foo" ) {
        wp_enqueue_style( 'foo-template-css' );
    }
}
add_action( 'wp_enqueue_scripts', 'foo_enqueue' );

Ref: https://developer.wordpress.org/reference/functions/get_page_template_slug/#more-information

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文