• Resolved jyogi

    (@jyogi)


    I want to change div class background color by fetching product category IDs. I wrote code using if else condition, but it is using last else condition even category IDs 49 or 50 is true.

    <?php
    if ( $category_ID == 49 ) {
    $color = ‘#FF0000’;
    } else if ( $category_ID == 50 ) {
    $color = ‘#0C2D4E’;
    } else {
    $color = ‘#00FF21’;
    }
    ?>

    <div class=”color” style=”background-color: <?php echo $color; ?>;”>
    <?php the_title( ‘<h1 class=”product_title entry-title”>’, ‘</h1>’ ); ?>
    </div>

Viewing 3 replies - 1 through 3 (of 3 total)
  • Typically there is a category name class added to both products in the loop and product pages. You can achieve your goal with CSS only.

    .product_cat-my-category .color {background-color:#fff}

    There is no such existing variable as $category_ID, that is why you are getting only ‘else’, you’d have to do it different way in PHP.

    madeincosmos

    (@madeincosmos)

    Automattic Happiness Engineer

    Hi @jyogi,

    Each product can have 0, 1, or more categories. You can use $product->get_category_ids(); to find all categories assigned to a product, but the result will be an array. If you’d like to assign a background color depending on product category, @superkot’s solution with CSS classes will be much easier to do this.

    Cheers!

    madeincosmos

    (@madeincosmos)

    Automattic Happiness Engineer

    Hi @jyogi,

    We haven’t heard back from you in a while, so I’ll mark this thread as resolved now. If you have some more questions, feel free to start a new one.

    Cheers!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Change background of div class using product category IDs’ is closed to new replies.