How can I link a CSS file only on single posts?

If I understand is_single() correctly, it’s only supposed to return true when the current “post” (in a generic sense) is a literal post (i.e., it has a post_type of post), and that it will return false when the current “post” is a page, attachment, etc. This is what the Codex says:

is_single() returns true if any single post is being displayed
is_singular() returns true when any page, attachment, or single post is being displayed.

But when I try to link a CSS file only into a post, it’s still included in attachment pages like http://example.com/?attachment=123456789. Here’s the code I’m using:

<?php if ( is_single() ) { ?>
    <link rel="stylesheet" href="https://wordpress.stackexchange.com/questions/65183/style.css" />
<?php } ?>

2 Answers
2

The Codex page for is_single should be updated, what you’re seeing is correct behavior. According to the main Conditional Tags Codex page:

is_single()

When any single Post (or attachment, or custom Post Type) page is being displayed. (False for Pages)

You can exclude attachments by also checking ! is_attachment().

Also, you may want to move that code into an enqueue style instead.

EDIT-

if ( is_single() && ! is_attachment() ) :
    echo 'is a single post and not an attachment';
endif;

Leave a Comment