0

I need help in styling the first post differently than the rest. What makes this differently is that I'm using this get_template_part in order for infinite scroll to work on my site.

This is what I use on index.php

<?php while (have_posts()) : the_post();
get_template_part( 'content', get_post_format() );
endwhile; ?>

which will load the loop from content.php. This was my old loop:

<?php if (have_posts()) : ?>
<?php $post = $posts[0]; $c=0;?>
<?php while (have_posts()) : the_post(); ?>
<?php $c++; if( !$paged && $c == 1) :?>

<-! first post -->

<?php else :?>

<-! the rest -->

<?php endif;?>
<?php endwhile; ?>
<?php endif; ?>

Thanks for the help.

2 Answers 2

3

If you are using post_class() in your content template like this …

<div <?php post_class(); ?>>

… you can filter that and add a special class:

add_filter( 'post_class', 'mark_first_post' );

function mark_first_post( $classes )
{
    remove_filter( current_filter(), __FUNCTION__ );
    $classes[] = 'first-post';
    return $classes;
}

Your first post in a loop will now have the class first-post. The nice thing is: this filter will run just one time and deactivate itself then.

You can also use another helper function:

function is_first_post()
{
    static $called = FALSE;

    if ( ! $called )
    {
        $called = TRUE;
        return TRUE;
    }

    return FALSE;
}

You can test for the first post then in your template:

if ( is_first_post() )
{
    // render the first post
}
else
{
    // the other posts
}
3
  • Will this work if I use the 'if' statement? <php if { link post <?php } elseif { ?> aside I'm asking because the first post will have a large image while the rest will use the thumbnail. Apr 28, 2013 at 4:18
  • @GregorySchultz Hm, in this case you need another way. See my update with an alternative.
    – fuxia
    Apr 28, 2013 at 4:31
  • First page: if ( 2 > get_query_var( 'paged' ) )
    – fuxia
    Apr 29, 2013 at 1:52
0

Got it to work!

<?php if ( 1 > get_query_var( 'paged' ) ) { ?>
<?php if ( is_first_post() ) { ?>
    first! <br />
    <?php the_title();?>
    <?php the_excerpt();?>
<?php } else { ?>
<?php the_title();?>
<?php the_excerpt();?>
<?php } ?>
<?php } else { ?>
<?php the_title(); ?>
<?php the_excerpt();?>
<?php } ?> 

You can see it in action - http://openbayou.staging.wpengine.com

Next question I have (same topic) is can this be cleaned up to make it simply as the code underneath is_first_page are duplicates

<?php } else { ?>
<?php the_title();?>
<?php the_excerpt();?>
<?php } ?>
<?php } else { ?>
<?php the_title(); ?>
<?php the_excerpt();?>
<?php } ?> 

Thank you so much for the help!

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.