Question

I want to put CSS inside a PHP file, because with that I can use 'conditional CSS', depending on the value of a customizer control.

My idea is to create a new php file, somewhere in my theme directory

./assets/css/header-conditional-styles.css

In this file I have created the following code:

<?php header("Content-type: text/css; charset: UTF-8"); ?>
<style>
    <?php if ( text == get_theme_mod( 'layout_logo', text ) ) : ?>
        .theme-header-title { color: green !important; }
    <?php else : ?>
        .theme-header-title { color: blue !important;}
    <?php endif; ?>
</style>

The code inside the is as an example.

In my functions.php file I tried to include the file like this:

require( get_template_directory()  . '/assets/css/header-conditional-styles.php');

I implemented this and I know have difficulty editing theme files. It gives me the message that my changes might not be saved and that I might try to upload them via FTP.

Please point me in the right direction on how to include the file and if the content of the php-file is correct? Thanks!

Was it helpful?

Solution

You might try conditional classes instead. In your regular "style.css" file you would include both classes:

.theme-header-title.green { color:green; }
.theme-header-title.blue { color:blue; }

(Tip 1: avoid !important, just use a more specific style if needed - for example, h1.theme-header-title.green.)

Then in your HTML, which is likely in your "header.php" file, you'd use the Customizer setting to add the green or blue class:

<?php
if ( text == get_theme_mod( 'layout_logo', text ) ) {
    $color = 'green';
} else {
    $color = 'blue';
}
?>
<h1 class="theme-header-title <?php echo $color; ?>"><?php the_title(); ?></h1>

This way you don't have to include an additional CSS file, or mix CSS with PHP.

(Tip 2: when adding CSS to WP, enqueue it rather than using require(). Similar to avoiding !important, it will allow you to adjust things later if needed.)

(Tip 3: make your changes in a child theme, instead of directly editing an existing theme. This way you won't lose your changes when the theme is updated.)

(Tip 4: it sounds like you're editing theme files directly in wp-admin. It's much safer to SFTP in, download a copy of the theme to work on, and upload files as needed.)

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top