If first post, style differently — Wordpress [closed]

三世轮回 提交于 2019-12-01 12:50:19

Append following codes after yours:

<?php if (have_posts()) : $postCount = 1; while (have_posts()) : $postCount++; ?>

<?php if($postCount == 2) { ?>
  // SOMETHING TO DO WITH FIRST POST
<?php } else { ?>
  // SOMETHING TO DO WITH ALL OTHER POSTS
<?php } ?>
<?php if (have_posts()) : $postCount = 0; while (have_posts()) : $postCount++; ?>

The above piece of code will create a $postCount variable and increment it every time The Loop loops. Note that I've changed it to start at 0 instead of 1.

We now have the post count in $postCount variable. We just need to find the first post and apply the styles to that post.

Normally, you'll have something like this:

<div class="post" id="post-<?php the_ID(); ?>">

Change that to:

<div <?php if($postCount == 1) { ?>class="YourSpecialClass"<?php } 
else { ?>class="post"<?php } ?> id="post-<?php the_ID(); ?>">

The above code will check if the $postCount is 1 (first post), and then add the class="YourSpecialClass" part as its <div> attribute.

A better readable version:

<?php if($postCount == 1) { ?>

    //the first post -- style it

<?php } else { ?>

    //other posts -- proceed normally

<?php } ?>

Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!