Category Conditional in Attachment.php (7 posts)

  1. 2bak860
    Posted 6 years ago #

    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.

  2. 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
  3. 2bak860
    Posted 6 years ago #

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

  4. @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 ...

  5. 2bak860
    Posted 6 years ago #

    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,


  6. gudlyf
    Posted 6 years ago #

    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.

  7. tgiokdi
    Posted 6 years ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic