Skip to content

Instantly share code, notes, and snippets.

@kontur
Created October 17, 2024 06:31
Show Gist options
  • Save kontur/1dd5e8ed163d2b0d88feae4d116fd3e8 to your computer and use it in GitHub Desktop.
Save kontur/1dd5e8ed163d2b0d88feae4d116fd3e8 to your computer and use it in GitHub Desktop.
Render CSS from PHP file with access to WP functions
// functions.php
add_action("wp_enqueue_scripts", "css_styles", 1000);
function css_styles()
{
// load previews
wp_enqueue_style( 'previews-css', '/previews');
}
// Add a rewrite rule.
add_action( 'init', function () {
add_rewrite_endpoint( 'previews', EP_ROOT );
});
// For requests to the /previews page, set a queryvar
add_filter( 'request', function ($vars) {
if (isset($vars["name"]) && $vars["name"] == "previews") {
$vars["previews"] = true;
}
return $vars;
});
// If there is a queryvar, render css instead
add_action( 'template_redirect', function () {
if (get_query_var("previews")) {
locate_template( 'includes/previews.php', TRUE, TRUE );
exit();
}
});
// includes/previews.php
status_header("200");
header('Content-Type: text/css;charset=utf-8');
WP_Query()...
// echo CSS
@kontur
Copy link
Author

kontur commented Oct 17, 2024

Make sure to cache the output CSS; this effectively initializes WP a second time for each request!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment