• Resolved linnieA

    (@linniea)


    Hello!

    Unfortunately, my php skills aren’t great, so I could really use some help on the following. I’m displaying related posts in single.php. Now I’d like to add the class .first to the first post en .last to the last post.

    Here’s the code I’m using:

    <div id="related">
    	<?php $orig_post = $post;
    	global $post;
    	$tags = wp_get_post_tags($post->ID);
    	if ($tags) {
    	$tag_ids = array();
    	foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
    	$args=array(
    	'tag__in' => $tag_ids,
    	'post__not_in' => array($post->ID),
    	'posts_per_page'=>5, // Number of related posts that will be shown.
    	'caller_get_posts'=>1
    	);
    	$my_query = new wp_query( $args );
    	if( $my_query->have_posts() ) {
    	echo '<div id="relatedposts"><h3>You might also like...</h3><div>';
    	while( $my_query->have_posts() ) {
    	$my_query->the_post(); ?>
    	<div class="fourcol"><div class="relatedthumb"><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_post_thumbnail( 'related' ); ?></a></div>
    	<div class="relatedcontent">
    	<h2><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2>
    	</div>
    	</div>
    	<? }
    	echo '</div></div>';
    	}
    	}
    	$post = $orig_post;
    	wp_reset_query(); ?>
    	</div>
Viewing 2 replies - 1 through 2 (of 2 total)
  • is this the location you need to add the CSS classes:
    <div class="fourcol">

    example, using the build-in loop variables:

    <div class="fourcol<?php if( $my_query->current_post == 0 ) { echo ' first'; } elseif( $my_query->current_post == $my_query->post_count-1 ) { echo ' last'; }; ?>">

    BTW:

    avoid using php shorttags – they are not enabled on every server.

    use wp_rest_postdata() after a custom WP_Query(), instead of wp_reset_query().

    Thread Starter linnieA

    (@linniea)

    SWEET! It works ?? Thank you very much alchymyth!

    Now I’ve got no clue what php shorttags are (I’ll try to find some info on it) and I’m not sure what you mean with the last comment. I’ve adjusted the last part to:

    }
    $post = $orig_post;
    wp_rest_postdata(); ?>
    </div>

    Is that correct?

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Add class to first and last div’ is closed to new replies.