How do I style Wordpress pages differently based on the tag used?
-
19-04-2021 - |
Pregunta
I was thinking this might be done by adding custom CSS to a page template. I have a page template like this:
<?php
/*
* Template Name: Grafy Full Width
*/
/*add_filter('materialis_full_width_page', '__return_true');*/
materialis_get_header();
?>
<div <?php echo materialis_page_content_atts(); ?>>
<div class="grafy-full-width-content">
<?php
while (have_posts()) : the_post();
the_content();
endwhile;
?>
</div>
</div>
<?php get_footer(); ?>
And I thought I might be able to add the CSS like this (basically I have 10 main tags and all I need to do is to change the header background, so I might just add 10 one-lined CSS files and condition them like this):
<?php function wpse_enqueue_page_template_styles() {
if (has_tag('Lesy')) {
wp_enqueue_style( 'Lesy', get_template_directory_uri() . '/css/Lesy.css' );
}
}
add_action( 'wp_enqueue_scripts', 'wpse_enqueue_page_template_styles' );?>
No matter what I do, this just isn't working. What could I be doing wrong? Many thanks!
Solución
If you used the body_class
and post_class
template tags, you get a CSS class added that contains classes for all the tags and terms a post has which you can use to conditionally style posts without needing to conditionally enqueue stylesheets
Otros consejos
You are using has_tag
outside of the loop. You must add the post ID to has_tag
. I also add property_exists
to be sure we have a post object and avoid warnings.
function wpse_enqueue_page_template_styles() {
global $post;
if (property_exists($post, 'ID') === true && has_tag('Lesy', $post->ID)) {
wp_enqueue_style( 'Lesy', get_template_directory_uri() . '/css/Lesy.css' );
}
}
add_action( 'wp_enqueue_scripts', 'wpse_enqueue_page_template_styles' );