• Resolved Guido

    (@guido07111975)


    Hi,

    I have a theme which displays my posts in 2 columns. I clear each left post. I currently use this wrapper around each post:

    <div class="post-home<?php if( $wp_query->current_post%2 == 0 ) echo ' left'; ?>">
    // post content
    </div>

    With CSS:

    .post-home {width:48%; float:left; margin:0;}
    .post-home.left {clear:left; margin:0 4% 0 0;}

    But I now want to support the post_class so I can use extra Post Formats such as Aside.

    That’s why I have to include the post_class to the loop (among other things ). Normally I can use something like this:

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

    But because I have to clear each left post I’ve build this:

    <?php if( $wp_query->current_post%2 == 0 ) : ?>
    <article id="post-<?php the_ID(); ?>" <?php post_class('post-home left'); ?>>
    <?php else : ?>
    <article id="post-<?php the_ID(); ?>" <?php post_class('post-home'); ?>>
    <?php endif; ?>
    // post content
    </article>

    Does work fine, but I’m wondering if this can be improved/fine-tuned?
    And should I use the article tag?

    Any thoughts?

    Guido

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    Guido my friend!

    You could just do
    <article id="post-<?php the_ID(); ?>" <?php post_class('post-home'); echo $wp_query->current_post % 2 ? '' : ' left'; ?>>

    Much more concise, but I’m not sure it’s that much more efficient. It’s also harder to read unless you’re familiar with ternary operators and the fact $value % 2 returns either true or false (same as 1 or 0).

    Whether you should use article is really “should I use HTML5?” The same arguments, pro or con apply.

    Use article for sure. If it’s news, use article. That’s what’s so nice about html5 is that it’s as semantic as you’d like.

    when using post_class() you can add CSS classes via a filter;

    https://codex.wordpress.org/Function_Reference/post_class
    https://codex.wordpress.org/Function_Reference/post_class#Add_Classes_By_Filters

    in your case, for example:

    function post_layout_class( $classes ) {
    	global $post;
    	if( $wp_query->current_post%2 == 0 ) $classes[] = 'left';
    	return $classes;
    }
    add_filter( 'post_class', 'post_layout_class' );
    Thread Starter Guido

    (@guido07111975)

    Hi guys,

    Thanks for your response, I certainly can go further with this.

    @bcworkz: friends 4ever 😉 😉

    Guido

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘Adding post_class to the loop’ is closed to new replies.