0

I have a new WP_Query on my archive page. I also have a post_class filter conditionally adding a class of first so I can display them in rows of 3 reliably.

This is the post_class filter

function sm_inline_post_class( $classes ) {
    global $wp_query;

    if( 0 == $wp_query->current_post || 0 == $wp_query->current_post % 3 )
        $classes[] = 'first';

    return $classes;
}
add_filter( 'post_class', 'sm_inline_post_class' );

This works fine for the default query, but the first class does not get applied to the posts from my custom query.

How do you conditionally apply post classes to entries from custom queries?

0

You are using the global $wp_query not your custom query. Either declare yours global too like global $wp_query_archives and then use that in the sm_inline_post_class callback while being aware of the drawbacks of using global variables or do a little work like so:

$class = sm_inline_post_class( array(), $my_custom_query );

And then pass $class as the first argument to your post_class call (I imagine you are using this function on your archive page).

Then, modify your sm_inline_post_class function like so:

function sm_inline_post_class( $classes, $query = null ) {
    global $wp_query;

    $query = ( $query == null ) ? $wp_query : $query;

    if( 0 == $query->current_post || 0 == $query->current_post % 3 ) {
         $classes[] = 'first';

    return $classes;
}

This however can always attach you 'first' if you are using your custom WP_Query nested in a $wp_query which happens to have the current_post set to a multiple of 3.

The even safer option would be to use a different function to get the class name:

$class = custom_inline_post_class( array(), $my_custom_query );

function custom_inline_post_class( $classes, $query ) {
    if( 0 == $query->current_post || 0 == $query->current_post % 3 ) {
         $classes[] = 'first';

    return $classes;
}

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.