0

Normally if I wanted to add a custom post class I would use the post_class filter.

However, when using a custom loop the post_class filter is not accessible.

I am trying to apply classes that will place posts into columns depending on the count. Here is the example code I would use when not using a custom loop;

    //Add Post Class Filter
add_filter('post_class', 'sk_post_class');

function sk_post_class($classes) {
    global $loop_counter;
    $classes[] = 'one-third';

    if (($loop_counter + 3) % 3 == 0) {
        $classes[] .= 'first';
    }

    $loop_counter++;
    return $classes;
}

Each post in my custom loop is wrapped with <div class = "answers"></div>. I am thinking that I need to be able to modify the code above to add classes to <div class = "answers"> based on the loop counter.

Can anyone point me in the right direction to how I might be able to achieve this?

  • the post_class filter works fine in custom loops if you've used the post_class function correctly. edit your question to add your custom loop code with the post_class function. – Milo Jul 11 '16 at 15:15
  • Thanks milo, that lead me to the answer I have posted below. – tmgale12 Jul 11 '16 at 16:02
0

As milo stated, I need to use the post_class function to use the post_class filter.

By adding <?php post_class(); ?> to the div in my loop I was then able to successfully modify the post class. Below is my full code containing the post_class filter and the post_class function.

Reference: https://codex.wordpress.org/Function_Reference/post_class

          <?php


      //Call in the header
      get_header();


          //Add Post Class Filter
      add_filter('post_class', 'sk_post_class');

      function sk_post_class($classes) {
          global $loop_counter;
          $classes[] = 'one-third';

          if (($loop_counter + 2) % 2 == 0) {
              $classes[] .= 'first';
          }

          $loop_counter++;
          return $classes;
      }


      $args = array (
        'post_type'  => array( 'test' ),
      );

      $query = new WP_Query( $args );

      if ( $query->have_posts() ) {
        while ( $query->have_posts() ) {
          $query->the_post(); ?>

          <div id="post-<?php the_ID(); ?>"<?php post_class(); ?>>

              <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>

          </div>

      <?php }
      } else {
        echo 'No posts found';
      }

      // Restore original Post Data
      wp_reset_postdata();


       // Call in footer 
      get_footer();

      ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.