Skip to content

Instantly share code, notes, and snippets.

@frankiejarrett
Last active July 17, 2017 09:33
Show Gist options
  • Select an option

  • Save frankiejarrett/5550855 to your computer and use it in GitHub Desktop.

Select an option

Save frankiejarrett/5550855 to your computer and use it in GitHub Desktop.
Add first and last classes to your WordPress loop without using JavaScript
<?php
/**
* Display the classes for the post div and automatically mark the first and last posts
*
* @param string|array $class One or more classes to add to the class list.
* @param int|WP_Post $post_id Optional. Post ID or post object.
*/
function fjarrett_post_class( $class = '', $post_id = null ) {
global $wp_query;
$class = ! empty( $class ) ? sprintf( '%s ', trim( $class ) ) : '';
if ( 0 === $wp_query->current_post ) {
$class .= 'first';
} elseif ( ( $wp_query->current_post + 1 ) === $wp_query->post_count ) {
$class .= 'last';
}
echo get_post_class( $class, $post_id );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment