• Resolved donhathuy

    (@donhathuy)


    Dear all,
    I want to apply the custom style for posts on the position of 1, 5, 10… of the loop but I get troubles about how to choose the right one. Can any show me how to do it.
    I use with get_posts() and WP_Query().
    Thank you.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Two approaches to this depending on your browser compatibility requirements.

    1) Front-end (CSS)

    You can use the :nth-child() declaration to apply styling to the 1, 5, 10… post on the page. You can find a demo/generator (and link to Chris’ in-depth article) here: https://css-tricks.com/examples/nth-child-tester/

    This would be my preferred method, but the downside is that IE only supports this from version 9+ – if that matters to you.

    2) Back-end (PHP)

    The other approach would be to add a class name to the 1, 5, 10… post during the loop. At the top of your loop, increase a variable, and then check it’s value to see if it qualifies for your special class name or not. If it does, you can pass the class name to post_class() in your markup.

    To check the value of your counter, you can use something like the modulus operator: https://php.net/manual/en/language.operators.arithmetic.php

    Thread Starter donhathuy

    (@donhathuy)

    Thank you for your suggestion.
    I will manage to do with loop because at the specific position, I have the different way to show the post.
    The problem is I can’t check the current position of posts in the loop with an interger. I have tried to use Swith/Case function, however, it only show the right layout, but no content at all.
    This is some code that I’ve used:

    <?php $recent = new WP_Query('posts_per_page=70');
     $i = $wp_query->current_post; // Start from the beginning of the loop
    swith ($i){
     case 1: case 6:
     // show the posts here
     break;
     case 5: case 10:
     // show the posts matched here
     break;
     default:
     // show the rest posts here
     break;
    }
    ?>

    Now how to check the current_post in loop with integer and what should be used to print the post content?
    Thanks.

    Thread Starter donhathuy

    (@donhathuy)

    I finally manage to do it. I forgot to change $wp_query->current_post into $recent->current_post, that’s why my $i always be -1 ??
    Thanks

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘How to apply "cases" for fixed positioned posts in a loop?’ is closed to new replies.