If first post, style differently — Wordpress [closed]

谁说胖子不能爱 提交于 2019-12-19 11:34:39

问题


I need the first post that was ever posted to be styled differently. Is there a way that I can see if the post is first, and then change its contents? I currently have a div in all my posts. This needs to be replaced with different div.

Apparently the following piece of code can help, but I'm not sure how to implemenet it:

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

I'm new with WordPress so not entirely sure how this could work?


回答1:


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 } ?>



回答2:


<?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!



来源:https://stackoverflow.com/questions/18357231/if-first-post-style-differently-wordpress

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