Jordan
Jordan

Reputation: 1642

How can I load a custom stylesheet in Wordpress for custom post types?

I have a custom post type, and I would like to only load a stylesheet for that custom post type.

I tried to load this from the template view for the custom post type. So I tried putting it in single-joiner.php. Also, I tried putting it in functions.php.

wp_enqueue_style( 'style-joiner', get_template_directory() . '/style-joiner.css' );

Essentially, I have a variety of custom post types, and I want to run a different stylesheet for each one. Can someone point me in the right direction?

Upvotes: 0

Views: 2915

Answers (1)

Xhynk
Xhynk

Reputation: 13860

Provided you're using the default action hook for enqueuing files, wp_enqueue_scripts(), you should have access to the global $post and all of it's attributes.

Inside of your enqueuing function, you should be able to check the current post type either by making use of the is_singular() function, or referencing the global $post->post_type value.

add_action( 'wp_enqueue_scripts', 'enqueue_frontend_assets', 10 );
function enqueue_frontend_assets(){
    if( is_singular( 'joiner' ) ){
        wp_enqueue_style( 'style-joiner', get_stylesheet_directory_uri() . '/style-joiner.css' );
    }
}

You could take it a step further and check the current post type, check to see if a style-{post_type}.css file exists, and then enqueue if it does - but if you just have the one post type, the above function should be enough to get you started.

edit: I apologize, I didn't notice before, but you're using the get_template_directory() function. That's returning a absolute system path, not the URI. You'll want to use the get_template_directory_uri() or get_stylesheet_directory_uri() functions to return the URI instead.

Upvotes: 1

Related Questions