• Resolved emangham

    (@emangham)


    Hello,

    I have a page template which is used to display blogs. Here is the code:

    <section class="news-list">
       <?php $the_query = new WP_Query( 'posts_per_page=5' ); ?>
       <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
    
             <div class="news-list__item" data-scroll-watch>
                <a href="<?php the_permalink() ?>">
                   <div class="news-list__item__image" data-bg-img="<?php the_post_thumbnail_url(); ?>"></div>
                   <div class="news-list__item__text" data-bg-color="#0088CF">
                      <p><?php foreach((get_the_category()) as $category) {
                         echo $category->cat_name . ' ';
                       } ?></p>
                   <p><?php the_title(); ?></p>
                </div>
             </a>
          </div>
    
       <?php
          endwhile;
          wp_reset_postdata();
       ?>
    </section>

    It works great, however I need to an IF statement in there. On the bit that says “#0088CF”, this colour must depend on the category that the post belongs to using slugs.

    So for example, if the post is in “thoughts” it is “#ff0000” else “social” it is “#000000” else “story” it is “#eeeeee”…

    Thank you!

Viewing 3 replies - 1 through 3 (of 3 total)
  • You may try something like this:

    <section class="news-list">
       <?php $the_query = new WP_Query( 'posts_per_page=5' ); ?>
       <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
    
             <div class="news-list__item" data-scroll-watch>
                <a href="<?php the_permalink() ?>">
                   <div class="news-list__item__image" data-bg-img="<?php the_post_thumbnail_url(); ?>"></div>
    
                      <?php
    		  foreach((get_the_category()) as $category) {
    
    		      // Define default color
    		      $bg_color = 'CCC';
    
    		      // Check if slug matches one of our slugs
    		      if ($category->slug == 'thoughts')
    		          $bg_color = '#F00';
    		      if ($category->slug == 'social')
    		          $bg_color = '#000';
    		      if ($category->slug == 'story')
    		          $bg_color = '#EEE';
    
    		      echo '<div class="news-list__item__text" data-bg-color="' . $bg_color . '">';
                          echo '<p>' . $category->cat_name . '</p>';
                       }
    				   ?>
                   <p><?php the_title(); ?></p>
                </div>
             </a>
          </div>
    
       <?php
          endwhile;
          wp_reset_postdata();
       ?>
    </section>
    Thread Starter emangham

    (@emangham)

    Legend, thank you!

    😉 You’re welcome!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘IF post is inside a specific category’ is closed to new replies.