0

I would like to add additional styles to the styles.css file before it is sent to the client. Is this possible?

Currently styles.css contains :

/*
Theme Name: My Theme
Theme URI: https://example.com/themes/vanilla/
...
*/

...

html {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    font-size: 62.5%;
    overflow-y: scroll;
    -webkit-text-size-adjust: 100%;
    -ms-text-size-adjust: 100%;
}

// MY ADDITIONAL CSS HERE

I would like to add additional CSS dynamically to the end of that file. Is that possible?

For example, in my index.php:

<?php 
if ( have_posts() ) : 

   while ( have_posts() ) : the_post();
   // normal post stuff


    moreCSS = $myPost->moreCSS;
    addMoreCSSToStyles_css(moreCSS);

    endwhile;
?>
2
  • This wouldn't be the most efficient method, you should either output it dynamically at runtime or enqueue a new stylesheet written by your code
    – Tom J Nowell
    Commented Oct 15, 2015 at 0:04
  • How would I enqueue it? Commented Oct 15, 2015 at 0:06

1 Answer 1

2

You can enqueue a different stylesheet only for index.php using conditional tags

The following code should be added in functions.php

/**
 * Proper way to enqueue scripts and styles
 */
function theme_name_scripts() 
{
 if ( is_home() ) 
 {      
      wp_enqueue_style( 'style-name',  get_template_directory_uri() .   "/path_to_file/yourStylesheet.css' ); 
 }
}

add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );
2
  • Thank you. In my case I don't have a CSS file to link to. What I want to do is add more CSS to the existing styles.css. From your link on enqueue I found this function, codex.wordpress.org/Function_Reference/wp_add_inline_style. I think that will do what I want but I'm not sure where to put it. Commented Oct 16, 2015 at 0:04
  • You can add it into the functions.php and call it with add_action '<?php function my_styles_method() { wp_enqueue_style( 'custom-style', get_template_directory_uri() . '/css/custom_script.css' ); $color = get_theme_mod( 'my-custom-color' ); //E.g. #FF0000 $custom_css = " .mycolor{ background: {$color}; }"; wp_add_inline_style( 'custom-style', $custom_css ); } add_action( 'wp_enqueue_scripts', 'my_styles_method' );' ?>
    – julia
    Commented Oct 20, 2015 at 13:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.