wp_register_style along with wp_enqueue_style
Here's how it operates:
Using wp_register_style allows you to create your own stylesheets and assign them unique handles. This feature permits you to define all your styles and only load them when necessary. Typically, stylesheets are registered early in the theme's process and then enqueued based on specific conditions.
For instance:
Let's assume you have a custom shortcode but want to load its stylesheets only when the shortcode is utilized:
functions.php
add_action('wp_enqueue_scripts', 'custom_enqueue_scripts');
function custom_enqueue_scripts()
{
//Register the style
wp_register_style('my-shortcode-styles', get_template_directory_uri() . '/css/shortcode-styles.css');
}
add_action('init', 'custom_init');
function custom_init()
{
//Example shortcode
add_shortcode('my_shortcode', 'custom_shortcode');
}
function custom_shortcode($atts, $content = null)
{
//If the registered style is not loaded....
if (!wp_style_is('my-shortcode-styles')) {
//Enqueue it!
wp_enqueue_style('my-shortcode-styles');
}
return 'My Shortcode!';
}
In most scenarios, wp_enqueue_style is sufficient. With this, you can both register and enqueue your stylesheets at the same time:
add_action('wp_enqueue_scripts', 'custom_enqueue_scripts');
function custom_enqueue_scripts()
{
//Register and enqueue the style
wp_enqueue_style('my-shortcode-styles', get_template_directory_uri() . '/css/shortcode-styles.css');
}
In your situation, you can use simple logic checks to decide which stylesheet to load based on the user's page:
add_action('wp_enqueue_scripts', 'custom_enqueue_scripts');
function custom_enqueue_scripts()
{
if(is_home()){ //is_front_page() if you have a Page set as the home page
//Load only on the home page
wp_enqueue_style('home-styles', get_template_directory_uri() . '/css/styles1.css');
}
//Load on all other pages
wp_enqueue_style('my-theme', get_template_directory_uri() . '/css/styles2.css');
}
Note: To ensure stylesheet enqueues work properly, your theme must utilize wp_head and wp_footer. If these are missing in your theme's template files, stylesheet enqueues will not function.
Additional resources: