I need to generate the CSS for my plugin from a function, how do i map a request to a function in the front-end?

This is forked from something I wrote for a similar requirement.

empty( $_GET['my-css-var'] ) || add_action( 'plugins_loaded', 'wpse_59089_css' );
function wpse_59089_css()
{       
    header( 'Content-Type: text/css' );

    // Aggressive caching to save future requests from the same client.
    $etag = '"' . md5( __FILE__ . $_GET['my-css-var'] ) . '"';

    header( 'ETag: ' . $etag );
    header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + 31536000 ) . ' GMT' );
    header( 'Cache-Control: public, max-age=31536000' );

    if ( empty( $_SERVER['HTTP_IF_NONE_MATCH'] ) || $etag != stripslashes( $_SERVER['HTTP_IF_NONE_MATCH'] ) ) {
        // Set all your variables here.
        $my_height = 100;

        // Render your CSS with a heredoc!
        $content = <<<CSS
#my_id {
    height: $my_height;
}
CSS;

        header( 'Content-Length: ' . strlen( $content ) );
        echo $content;

    } else {
        // Not modified!
        status_header( 304 );
    }

    // We're done!
    exit;
}

And the resource link would simply be:

http://example.com/?my-css-var=20120719_or_static_hash.css

Whenever the CSS was changed (typically after a settings update), change the datestamp/hash in the URL to force-refresh.

If you’ve switched etags off at the server level, you’ll need to resort to sending and checking “last modified” instead.

Update:

Don’t use a link. Extra http requests are evil. Put your dynamic CSS inline. Really. Even google recommends it.

It all depends. Unless the CSS weighs in tiny, or it’s only for a one-off page with low repeat visits, then yeah, inline might be the way to go.

But an aggressively cached external stylesheet will only trigger a request on first access (for the large majority of clients*).

Every new visitor to the site will have to download the CSS one way or another. But inline styles are sent for every subsequent view, whereas the external will hit the local cache.

Take a 1000 visitors, 10 hits each, 500 bytes of CSS. Inline will fatten up the bandwidth an additional ~4MB**. Might not seem much, but bump the CSS size, or the hits per visitor, and it’ll continue to creep.

Like I said to start with, it all depends! How large is the CSS? Where is it used?
Do you have a high ratio of new to loyal visitors? (*Is most of your audience behind a proxy?) (**Are you implementing “Not Modified” on your HTML?)

I guess the point I’m making is that “HTTP requests are evil” isn’t gospel, even if it was spouted from the mouth of Google 😉

I’m still of the opinion that anything more than a few lines belongs in an external stylesheet, coupled with a tight set of caching rules, but that suits me, not everyone!