Support » Fixing WordPress » Category Conditional in Attachment.php

  • I’m trying to make a conditional tag in attachment.php, so that, depending which category the post is in, the attachment will show different content.

    Anyone have a solution? Thanks, Ross.

Viewing 6 replies - 1 through 6 (of 6 total)
  • These pages from the codex may get you started:

    I’m thinking the in_category() conditional may be what you are looking at with something like:

      if ( (in_category('my-cat')) ) {
        // special 'my-cat' post attachment display code
      } else {
        // other category post attachment display

    Thanks Cais. in_category won’t work because attachments don’t recognise in_category, only post>parents.

    @2bak860 – After some further reading, I see what you mean.

    Perhaps I misunderstood your original question …

    Are you trying to change the actual attachment, or just change the look of the page the attachment is being displayed on?

    For example, if attachment X is being displayed, show a blue background; and, if attachment Y is being displayed, show a red background. (I’m using background color for simplicity sake.) If this is the case, I would suggest implementing the body_class() template tag using the CSS classes it generates to re-style the attachment page(s) explicitly.

    Hope that helps …

    Hi Cais,

    Thanks for your reply! I am trying to change the layout of the attachment.php page depending on the category we’re in – it goes a bit further than CSS I’m afraid.

    Desired in attachment.php :.

    <?php if ( in_category('pears')  ){ ?>
    show pears
    <?php } elseif ( in_category('apples') ) { ?>
     show apples
    <?php } ?>

    thanks so much for your help,


    2bak860 —

    It looks like you can grab the post parent and then check its category:

    $post = get_post($ID);
    if ( is_object($post) ) :
      if ( ('attachment' == $post->post_type) && $post->post_parent && ($post->ID != $post->post_parent) ) :
         if ( in_category('pears') ) { echo "pears"; }

    Something like that.

    I’m trying to do this same thing, but I am having troubles with image attachments that were originally in category “1”, but then edited to category “X”, and the attachment.php file still showing the “1” template, which is not the behavior that I would expect.

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Category Conditional in Attachment.php’ is closed to new replies.