WordPress.org

Ready to get started?Download WordPress

Forums

Changing appearance of all posts in one category on main page (6 posts)

  1. julianj
    Member
    Posted 6 years ago #

    I haven't been able to find anything that addresses this specifically. I'm trying to change the background color of every post in a certain category as it displays on the main page. Any ideas?

  2. Sivar
    Member
    Posted 6 years ago #

    Yes, with some php and a separate css-design for posts of one category. First, while in the loop, you need to determine the post's category-ID. Name would work, too, but it's easier with numbers. This article will help you to do so.

    Then you want to check, if the post belongs to that specific category. If it does, the div (which contains the post) shall have the class .post-cat10, while everything else gets just .post, or whatever class they get now.

    In the end, it will look similar to this:

    <?php if (have_posts()) : while (have_posts()) : the_post; ?>
    <?php foreach((get_the_category()) as $cat) $id = $cat->cat_ID; ?>
    <?php if ($id == 10) { ?>
    <div class="post-cat10">
    <?php } else { ?>
    <div class="post">
    <?php } ?>

    // loop content

    <?php endwhile; endif; ?>

    However, if you want specific colors for more than one category, you should integrate $id directly into the div instead of doing it with if-conditions.

    Then, all you have to do, is to create a class ".post-cat10" in your style.css, that matches ".post" except for the background-color. Et voila ;).

  3. julianj
    Member
    Posted 6 years ago #

    you rock! thanks so much!

  4. spiritbased
    Member
    Posted 6 years ago #

    "However, if you want specific colors for more than one category, you should integrate $id directly into the div instead of doing it with if-conditions."

    How does one do this please?

  5. thepete
    Member
    Posted 6 years ago #

    Yes, indeed--I'd like to know how to do that as well.

    perhaps

    <div class="<?php foreach((get_the_category()) as $cat) $id = $cat->cat_ID; ?>">

    ?

    I've managed to lose the code to pull the cat ID and the codex says it's been "deprecated". Which I believe just means "phased out."

  6. MichaelH
    Member
    Posted 6 years ago #

    The_Loop_in_Action presents information on that topic.

Topic Closed

This topic has been closed to new replies.

About this Topic