admin管理员组文章数量:1134248
How would you include a stylesheet
in both the block-editor
and on the front-end
if the page meets certain criteria?
In this case I want to include a stylesheet
called homepage.css
if the page is the home page only. I therefore did this:
add_action('enqueue_block_assets', function () {
if(is_front_page()){
wp_enqueue_style(
'homepage-stylesheet',
get_template_directory_uri() . '/homepage.css',
);
}
});
Whilst the code works on the front-end
it does not in the block-editor
as it appears that is_front_page()
cannot be determined until the page is rendered.
How would you go about this?
How would you include a stylesheet
in both the block-editor
and on the front-end
if the page meets certain criteria?
In this case I want to include a stylesheet
called homepage.css
if the page is the home page only. I therefore did this:
add_action('enqueue_block_assets', function () {
if(is_front_page()){
wp_enqueue_style(
'homepage-stylesheet',
get_template_directory_uri() . '/homepage.css',
);
}
});
Whilst the code works on the front-end
it does not in the block-editor
as it appears that is_front_page()
cannot be determined until the page is rendered.
How would you go about this?
Share Improve this question asked Oct 4, 2023 at 14:10 WalrusWalrus 1314 bronze badges 8 | Show 3 more comments1 Answer
Reset to default 0This can be done. @TomJNowell does point out the potential for a problem with this solution in the comments to the question but I cannot replicate that problem in any test.
In this example I locked on to the template slug. Therefore for this to work instead of using is_front_page() or similar, create a template called homepage and use it only for the homepage. Then do the same for any other pages you want to have a custom stylesheet.
add_action('enqueue_block_assets', function () {
global $post;
$template = get_page_template_slug($post->ID);
wp_enqueue_style(
$template . '-template-styles',
get_template_directory_uri() . '/' . $template . '.css',
);
});
本文标签: cssEnqueue Stylesheet on the front end and in the block editor Conditionally
版权声明:本文标题:css - Enqueue Stylesheet on the front end and in the block editor Conditionally 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736783084a1952707.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
.home
rule and take advantage of the body classes WP adds to help with this. Otherwise what you want is impossible if you ever plan to use the template or site editors as there's no way to know from PHP since the user can click into another template and it would be broken – Tom J Nowell ♦ Commented Oct 4, 2023 at 15:26enqueue_block_assets
may not be the ideal action to do that on, and there are definitely disadvantages to this approach and additional complexity, it's not the silver bullet it first appears to be – Tom J Nowell ♦ Commented Oct 5, 2023 at 13:44