WordPress.org

Forums

How to get dynamic stylesheets to work in wordpress! (3 posts)

  1. kwatts22
    Member
    Posted 1 year ago #

    I searched many wordpress forums trying to figure out how to add dynamic stylesheets to wordpress. I had no success but finally managed to get it working so that lead me to writing this tutorial.

    In order for it to work correctly you need to create a file in the same directory as your style.css. In this tutorial we will name the dynamic stylesheet to custom.css.

    First open your header.php file and find the following
    <link href="<?php bloginfo('stylesheet_url');?>" rel="stylesheet">

    right below it add the following
    <link rel='stylesheet' type='text/css' href="<?php bloginfo( 'url' ); ?>/?my-custom-content=css" />

    by adding the line below this will take higher priority over the regular style.css file.

    Next open your functions.php and add the following code at the bottom just before the cloasing ?> tag.

    add_action( 'parse_request', 'my_custom_wp_request' );
    function my_custom_wp_request( $wp ) {
        if (
            !empty( $_GET['my-custom-content'] )
            && $_GET['my-custom-content'] == 'css'
        ) {
            # get theme options
            header( 'Content-Type: text/css' );
            require dirname( __FILE__ ) . '/custom.php';
            exit;
        }
    }

    If you want to use a different name then custom.php make sure to change the above /custom.php it to whatever filename that you want to use. I tried to put it in a separate folder but wordpress will not recognize it.

    Now your ready to add styles to your custom.php like you would normally enter in a regular style.css

    body{
      background-color: #ffffff;
    }

    And that is how easy it is to add a dynamic stylesheet to your wordpress site.

  2. Rod Whiteley
    Member
    Posted 1 year ago #

    Looks like a weird solution to me. What problem does it solve?

    Also, when the theme updates it will destroy the changes you have made. Theme modifications are best done in a child theme.

  3. kwatts22
    Member
    Posted 1 year ago #

    I am using it to create theme options. You can put it in a child theme to save them from getting destroyed during a update.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.