- This topic has 7 replies, 2 voices, and was last updated 9 years, 4 months ago by Tom.
-
AuthorPosts
-
December 4, 2014 at 1:23 pm #51274Michael
Hello again,
I’m attempting to style the latest post appearing on the home page of my website. However most solutions I’ve found on WordPress support have you trying to alter code in the index.php file, where the Loop is controlled. Another purely CSS solution, where you specify the first instance of the article tag–.container article:first-child–didn’t work when I tried it. Instead it changed the class style all of the elements I was targeting, instead of a subclass.
What I want to do is detect if the current post is the latest post, and apply either alternate CSS styles or a different HTML block altogether. I would like to do this from functions.php of my child theme. Is this feasible?
I’ve sent a link to the website to support@generatepress.com.
December 4, 2014 at 1:58 pm #51302TomLead DeveloperLead DeveloperHi Michael,
How about adding a class to the first post in the loop using a function?
add_filter( 'post_class', 'generate_first_post_class' ); function generate_first_post_class( $classes ) { global $wp_query; if( 0 == $wp_query->current_post ) : $classes[] = 'first'; endif; return $classes; }
Then you can target that first post easily.
Let me know π
December 5, 2014 at 12:50 pm #51642MichaelHi Tom,
Thanks for the help. So far I’ve tried to implement this code by inserting it at the end of functions.php, then creating these classes in styles.css for targeting the specific object:
.first {} .first > ... > .meta-date { ... }
However in spite of the css styles, I end up with a 500 Internal Server Error. I’ll continue to work on this to see what the issue is, but I’d appreciate any insights on what the issue might be.
December 5, 2014 at 6:09 pm #51765TomLead DeveloperLead DeveloperThat’s weird – I just adjusted the code, give it a try and let me know if you still encounter an error.
December 8, 2014 at 7:11 am #52551MichaelThe code looks the same to me. In either case, same error. Maybe there is something odd I’m doing in my functions.php file that’s generating the error.
December 8, 2014 at 10:10 am #52680TomLead DeveloperLead DeveloperI played with this a little bit more, tested it and have it working.
add_filter( 'post_class', 'generate_first_post_class' ); function generate_first_post_class( $classes ) { global $wp_query; if( 0 == $wp_query->current_post ) : $classes[] = 'first'; endif; return $classes; }
If that still doesn’t work, it may be the code snippets plugin, and we’ll have to add it in a different way.
Let me know π
December 8, 2014 at 11:35 am #52734MichaelA-ha, that did it! So WordPress didn’t like having the return statement before exiting the conditional block. Perfect. Thank you very much Tom, once again.
December 8, 2014 at 3:01 pm #52805TomLead DeveloperLead DeveloperAwesome, glad it worked π
-
AuthorPosts
- You must be logged in to reply to this topic.