Include CSS with PHP without including wp-load?

I have a CSS-file generated from PHP.

In my file it says…

Read More
header("Content-type: text/css");
define('WP_USE_THEMES', false);
include '../../../../wp-load.php';

I’ve read that including wp-load.php like this is not good. Why I do this is to get the environment in there.

What is the “correct” way of doing this?

Related posts

Leave a Reply

1 comment

  1. EDIT

    Forget my answer below. You could simply use wp_register_style and wp_enqueue_style described in this answer.


    You could do it with an additional query variable.

    1. Add a new variable to the $query_vars array with the query_vars filter
    2. On the template_redirect action, make sure your custom.php-css file is included, if the query variable is set.

      // functions.php
      function wpse26013_add_query_vars(query_vars) {
          $query_vars[] = 'style';
          return $query_vars;
      }
      add_filter('query_vars', 'wpse26013_add_query_vars');
      
      function wpse26013_include_custom_css() {
          $style = get_query_var('style');
      
          if($style == 'custom') {
              include_once(get_stylesheet_directory_uri() . '/css/custom.php');
              return;
          }
      }
      add_action('template_redirect', 'wpse26013_include_custom_css');
      

    Then you can add a simple css include in your header file.

    // header.php
    <link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo('stylesheet_url') . '/css/?style=custom'; ?>" />
    

    Last but not least, you have to define your custom css file.

    // custom.php
    <?php
    header('Content-type: text/css');
    header("Cache-Control: must-revalidate");
    header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 1209600) . ' GMT');
    
    $options = get_option('webeo');
    ?>
    #header #logo {
        background: url('<?php echo get_stylesheet_directory_uri() . '/images/' . $options['header']['site_logo']; ?>') no-repeat;
    }
    

    You could also get the contents from the css file with the builtin PHP function file_get_contents() and print the css directly to the sourcecode.