Add CSS to CPT
November 26, 2024 ยท AI Conversations
### Code Example:
function custom_enqueue_css_for_single_cpt() {
// Check if we're on a single page and of the specific custom post type.
if (is_singular('your_custom_post_type')) {
wp_enqueue_style(
'custom-cpt-style', // Handle for the stylesheet.
get_stylesheet_directory_uri() . '/css/custom-cpt-style.css', // Path to your CSS file.
array(), // Dependencies.
'1.0.0', // Version number.
'all' // Media type.
);
}
}
add_action('wp_enqueue_scripts', 'custom_enqueue_css_for_single_cpt');
### Steps:
1. Replace `your_custom_post_type` with the slug of your custom post type.
2. Replace `/css/custom-cpt-style.css` with the path to your CSS file relative to your theme directory.
3. Save the code in your theme's `functions.php` file or in a custom plugin.
### Explanation:
– **`is_singular('your_custom_post_type')`**: Checks if the current page is a single page of the specified custom post type.
– **`wp_enqueue_style`**: Adds your CSS file to the page.
### Alternative: Inline CSS
If you prefer to include inline CSS instead of a separate file:
function custom_inline_css_for_single_cpt() {
if (is_singular('your_custom_post_type')) {
echo '<style>
.your-css-class {
color: #333;
font-size: 18px;
}
</style>';
}
}
add_action('wp_head', 'custom_inline_css_for_single_cpt');
This approach is useful for small style changes without needing a separate file.
### Example 1: Using `get_the_ID()`
The `get_the_ID()` function works inside **The Loop** or on single post pages.
$post_id = get_the_ID();
echo $post_id;
### Example 2: Using the `$post` Global Variable
If you're outside The Loop, you can use the `$post` global variable:
global $post;
$post_id = $post->ID;
echo $post_id;
### Example 3: Using `get_queried_object_id()`
For more generic cases, like outside single post templates or The Loop, you can use `get_queried_object_id()`:
$post_id = get_queried_object_id();
echo $post_id;
### When to Use Each Method:
– **`get_the_ID()`**: Use this inside The Loop or single post pages.
– **`$post->ID`**: Use this when accessing the global `$post` variable outside The Loop.
– **`get_queried_object_id()`**: Use this for retrieving the ID of the queried object, such as on a post, page, or archive template.
### Example in Context:
If you want to add the current post ID to the body class, for instance:
add_filter('body_class', function ($classes) {
if (is_singular()) {
$classes[] = 'post-id-' . get_the_ID();
}
return $classes;
});
This will append the current post ID as a CSS class to the “ tag.