Forums

Target and add class to element in if statement based on slug (7 posts)

  1. drhodes
    Member
    Posted 8 months ago #

    I'm creating a custom post type called events. I have created a taxonomy for event type with two categories, webinars and live-events. I'm trying to create a loop that will list these posts and apply a class to a span inside each list item if it is in the "webinars" category. I figured I could do this by targeting it's slug. I'm a bit stuck on how to write this, but I feel I must be close. Here's my attempt. Any help would be much appreciated.

    <ul class="eventlist">
    <?php $args = array( 'post_type' => 'event', 'posts_per_page' => 3 );
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post(); ?>

    <li class="event">

    <?php if ($tag->slug == 'webinar'){ ?>
    <span class="fevdate web">
    <?php }
    else { ?>
    <div class="fevdate">
    <?php } ?>

    <?php the_title(); ?></span><!--/fevdate-->

    <?php endwhile; ?>

  2. NateJacobs
    Member
    Posted 8 months ago #

    Good news is WordPress has you covered with some built in functions: post_class() and get_post_class(). Each post can already have a class of the category name or id. Read through the two Codex articles to get a feel for how it works.

    http://codex.wordpress.org/Function_Reference/post_class
    http://codex.wordpress.org/Function_Reference/get_post_class

  3. drhodes
    Member
    Posted 8 months ago #

    I messed with this for about an hour and can't seem to figure it out. Care to share an example working off my scenario above?

  4. NateJacobs
    Member
    Posted 8 months ago #

    Turns out I misread your original question. I am sorry. I thought you wanted to add an additional class to the post class.

    You'll want to use in_category(). I'll post an example in just a min.

  5. NateJacobs
    Member
    Posted 8 months ago #

    <?php
    
    if ( in_category( 'Webinar' ) )
    {?>
    	<span class="fevdate web"><?php the_title(); ?></span>
    <?php}
    else
    {?>
    	<div class="fevdate web"><?php the_title(); ?></div>
    <?php}
    
    ?>
  6. drhodes
    Member
    Posted 8 months ago #

    Thanks again for your help.
    I think I've done a poor job of describing what I'm trying to do. The in_category route seems to be on the right track, but I'm not using categories.
    It's a custom post type that doesn't use categories. I have a taxonomy of Event Type with options of Webinar or Live-Event. Is there a way to do what you've done but for the taxonomy term of Webinar?

  7. NateJacobs
    Member
    Posted 8 months ago #

Reply

You must log in to post.

About this Topic