• I’m trying to have one of two images show up in my posts depending on the category the post is filed in.

    I have 2 categories and 2 images.

    So if I have a post in category “food,” then the image specified for food should show up in the post.

    If I have a post in category “sports,” then the image specified for sports should show up in the post.

    How do I accomplish this with custom fields? I can’t seem to find information how to accomplish this. I’d greatly appreciate it.

Viewing 5 replies - 1 through 5 (of 5 total)
  • Do you have to use custom fields? Why not just use in_category()? Eg:

    <?php
    if ( in_category( 'food' )) $img = 'food.jpg';
    elseif ( in_category( 'sports' )) $img = 'sports.jpg';
    ?>
    <img src="full_ url_to/<?php echo $img;?>" width="xx" height="yy" alt="" />
    Thread Starter jimmyk1006

    (@jimmyk1006)

    Hi esmi,

    I placed that code in my template but the images aren’t showing up for me.

    Did you code this below correctly?

    <img src="full_ url_to/<?php echo $img;?>" width="xx" height="yy" alt="" />

    I placed the full url to the image in the code here >> $img = 'https://www.mywebsite.com/food.jpg';

    Did I do that correctly? I feel like the conflict is arising from either how you coded that snippet or how I used the full-length url to an image.

    <?php
    if ( in_category( 'food' )) $img = 'food.jpg';
    elseif ( in_category( 'sports' )) $img = 'sports.jpg';
    ?>
    <img src="https://www.mywebsite.com/<?php echo $img;?>" width="xx" height="yy" alt="" />

    should work. Is https://www.mywebsite.com your WP site? Have you checked the image urls?

    Thread Starter jimmyk1006

    (@jimmyk1006)

    That worked a charm!

    What I had to do for the image url was erase the domain – making this the final result: $img = 'wp-content/uploads/2012/06/sports.gif';

    Once again, thank you for saving me more endless hours trying to find the answer!

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Custom fields question’ is closed to new replies.