To integrate Tailwind CSS CDN scripts and pass configuration via PHP in WordPress, you need to follow these steps:
- Use the
wp_enqueue_scripts
hook to load Tailwind CSS and your custom configuration script. - Rebuild the
tailwind.config
via a PHP array, and then convert it into JSON format for use in JavaScript.
Here’s an example of the code:
function enqueue_tailwind_cdn() {
// Enqueue Tailwind CSS via CDN
wp_enqueue_script('tailwind-cdn', 'https://cdn.tailwindcss.com', array(), null, true);
// Create the Tailwind configuration in PHP
$tailwind_config = array(
'theme' => array(
'extend' => array(
'colors' => array(
'clifford' => '#da373d', // Your custom colors
),
),
),
);
// Convert the array to JSON
$tailwind_config_json = json_encode($tailwind_config);
// Add an inline script to configure Tailwind with the settings
wp_add_inline_script('tailwind-cdn', "
tailwind.config = $tailwind_config_json;
");
}
add_action('wp_enqueue_scripts', 'enqueue_tailwind_cdn');
Explanation:
- Enqueue Tailwind CSS via CDN:
wp_enqueue_script('tailwind-cdn', 'https://cdn.tailwindcss.com', array(), null, true);
— This loads Tailwind CSS from the CDN.- The
true
parameter inwp_enqueue_script
specifies that the script should be loaded at the bottom of the page.
- Tailwind configuration via PHP array:
- We create a PHP array with the configuration, where in the
extend
section we add your custom styles (e.g., custom colorclifford
).
- We create a PHP array with the configuration, where in the
- Converting the array to JSON:
- We use
json_encode()
to convert the PHP array into JSON, which can be embedded into the JavaScript.
- We use
- Adding the configuration script to the page:
wp_add_inline_script
inserts the JSON configuration directly into the page, after the main Tailwind script.
This code will load Tailwind CSS via the CDN and configure the theme, extending it with custom colors or other settings.