I am trying to make a new attachment page in a WordPress child theme.
I have created image.php and in my functions I am trying to get a new CSS file to load. I already have this for archive page and seems to be working OK. I have tried adding is page template (image.php) and is attachment, but doesn't seem to work
if (is_archive()) {
wp_enqueue_style( 'newlayout-style' , get_stylesheet_directory_uri() . '/layouts/archive.css');
} elseif (is_page_template('image.php')) {
wp_enqueue_style( 'newlayout-style' , get_stylesheet_directory_uri() . '/layouts/attachment.css');
} elseif (is_attachment()) {
wp_enqueue_style( 'newlayout-style' , get_stylesheet_directory_uri() . '/layouts/attachment.css');
}
Two points need to be understood:
1) is_page_template
function is useful to determine the current Page Template (if used), Page Template is different concept then Template Hierarchy. You can check in codex for further details:
2) In functions.php
, you need to determine if image attachment is getting displayed, in this case as @PieterGoosen has correctly pointed out, you need to use is_single
and is_attachment
template tags, additionally you can check if the attachment mime-type
is image, so code should be like:
function add_css_conditionally() {
if (is_archive()) {
wp_enqueue_style( 'newlayout-style' , get_stylesheet_directory_uri() . '/layouts/archive.css');
} elseif (is_single() && is_attachment()) {
if(stripos($wp_query->post->post_mime_type, 'image') !== false) {
wp_enqueue_style( 'newlayout-style' , get_stylesheet_directory_uri() . '/layouts/attachment.css'); // for image attachments, should be different css file.
} else {
wp_enqueue_style( 'newlayout-style' , get_stylesheet_directory_uri() . '/layouts/attachment.css');
}
}
}
add_filter('wp_enqueue_scripts', 'add_css_conditionally');