Created
October 17, 2024 06:31
-
-
Save kontur/1dd5e8ed163d2b0d88feae4d116fd3e8 to your computer and use it in GitHub Desktop.
Render CSS from PHP file with access to WP functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Make sure to cache the output CSS; this effectively initializes WP a second time for each request!