如何 link 自定义样式表到页面模板?

How to link a custom stylesheet to a page template?

如果有人能帮我解决这个问题,我将不胜感激。 我知道这是一个经常被问到的问题,但是我花了几天时间查看其他人的帖子,试图弄清楚如何使用我的函数文件夹 link 自定义样式表到我正在使用的页面模板正在处理。

到目前为止,我发现最有可能工作的代码是这个 -

if( is_page_template( 'work.php' ) ) {
wp_register_style("work-style", get_template_directory_uri() . 
"/css/page-template.css", '', '1.0.0');
wp_enqueue_style('page-template');
}

我尝试创建的页面模板名为 "work",因为我已尝试将其添加到代码中,但是我正在做的事情不正确,因为它要么使用 main样式表或者它没有任何效果,在我的页眉和页脚之间留下一个空白页。

您可以在下面查看我的页面模板 php 的代码。 (总的来说,我对 wordpress 和编码还很陌生,所以如果我犯了任何愚蠢的错误,请告诉我)。我从头开发了我正在使用的主题。

<?php
/*
Template Name:work
*/
?>

<link href="style.css" rel="stylesheet" type="text/css">

<link href="<?php bloginfo('stylesheet_url'); ?>" rel="stylesheet"  
type="text/css"> 

<body>

<?php get_header(); ?>

<div class="content" id= "workcontent">

<?php if (have_posts()) : ?>

<?php while (have_posts()) : the_post(); ?>

<div <?php post_class(); ?> id="post-<?php the_ID(); ?>">

<div class="entry">
<?php the_content(__('Read the rest of this entry &raquo;', 'kubrick')); ?>
</div>

</div>

<?php endwhile; ?>

<?php endif; ?>

<div id="wrapper">      

<a href="/landscapes"><div class="albums" id= "album1"></div></a>
<a href="/seascapes"><div class="albums" id= "album2"></div></a>
<a href="/macro"><div class="albums" id= "album3"></div></a>
<a href="/cities"><div class="albums" id= "album4"></div></a>
<a href="/long-exposure"><div class="albums" id= "album5"></div></a>
<a href="/miscellaneous"><div class="albums" id= "album6"></div></a>

</div>
</div>

</body>

<?php get_footer(); ?>

假设您的作品模板在主题文件夹的根目录下,实际名为work.php,同时您的css在css子文件夹中并被称为 template.css,您可能需要按如下方式修改您的代码:

function enqueue_styles() { 
    if( is_page_template( 'work.php' ) ) {
        wp_enqueue_style('work-style', get_bloginfo('template_url').'/css/page-template.css', true, '1.0.0', 'all' );
    }
}
add_action('wp_enqueue_scripts', 'enqueue_styles');

显然,这会进入您的 functions.php 文件。您也可以将其直接放在 work.php 文件中,在这种情况下,您可以跳过 if 并将以下行放在顶部:

wp_enqueue_style('work-style', get_bloginfo('template_url').'/css/page-template.css', true, '1.0.0', 'all' );

排队样式时,您需要使用注册它时使用的句柄名称,而不是文件名。在这种情况下,您将样式注册为 "work-style",因此您应该使用该名称将其入队,如下所示:

if( is_page_template( 'work.php' ) ) {
    wp_register_style('work-style', get_template_directory_uri() . 
    '/css/page-template.css', '', '1.0.0');
    wp_enqueue_style('work-style');
}