I have many custom post types, including some introduced by plugin such as bbPress or WooCommerce.
My standard stylesheet is growing large, so I thought to split it into multiple stylesheets according to post types being viewed in the browser. In this way, when the users is viewing bbpress fourms, he will also load a forum.css; when viewing wordpress pages, he would load a page.css. And so on.
I tried with the following code added in my functions.php:
function sg_frontend_enqueue_styles(){
$templateuri = get_template_directory_uri();
// some of my custom post types
if( get_post_type() == ( 'activity' OR 'dining' OR 'heritage' OR 'hiking' OR 'nightlife' ) ) :
wp_enqueue_style( 'locations', $templateuri.'/css/locations.css', '', false, 'all' );
// bbPress forums
elseif ( get_post_type() == ( 'forum' OR 'topic' OR 'reply' ) ) :
wp_enqueue_style( 'forum', $templateuri.'/css/forum.css', '', false, 'all' );
// Pages
elseif ( get_post_type() == 'page' ) :
wp_enqueue_style( 'page', $templateuri.'/css/page.css', '', false, 'all' );
// WooCommerce
elseif ( get_post_type() == 'product' ) :
wp_enqueue_style( 'product', $templateuri.'/css/product.css', '', false, 'all' );
endif;
add_action('wp_print_styles', 'sg_frontend_enqueue_styles');
However this is not working. Problem: all CSS styles are loaded altogether, regardless of whether the user is displaying a post belonging to that specific post type. Furthermore, 'page.css' is not being included at all.
I've then tried with a different approach, replacing conditionals with a switch:
$templatename = get_post_type();
switch ( $templatename ) :
case 'activity' :
wp_enqueue_style( 'locations', $templateuri.'/css/locations.css', '', false, 'all' );
case 'dining' :
wp_enqueue_style( 'locations', $templateuri.'/css/locations.css', '', false, 'all' );
case 'forum' :
wp_enqueue_style( 'forum', $templateuri.'/css/forum.css', '', false, 'all' );
case 'heritage' :
wp_enqueue_style( 'locations', $templateuri.'/css/locations.css', '', false, 'all' );
case 'hiking' :
wp_enqueue_style( 'locations', $templateuri.'/css/locations.css', '', false, 'all' );
case 'nightlife' :
wp_enqueue_style( 'locations', $templateuri.'/css/locations.css', '', false, 'all' );
case 'page' :
wp_enqueue_style( 'page', $templateuri.'/css/page.css', '', false, 'all' );
case 'product' :
wp_enqueue_style( 'product', $templateuri.'/css/product.css', '', false, 'all' );
case 'reply' :
wp_enqueue_style( 'forum', $templateuri.'/css/forum.css', '', false, 'all' );
case 'topic' :
wp_enqueue_style( 'forum', $templateuri.'/css/forum.css', '', false, 'all' );
break;
default : '';
endswitch;
this one sometimes work sometimes not... On bbpress forums works fine, but on pages for example, it enqueues ALL the stylesheets...