• I want to style specific posts in a list differently.

    For example, in a list of ten, the second and third would look slightly different.

    I would like to do this by applying number classes to the post like this:

    <div class=”post1″>Post1</div>
    <div class=”post2″>Post2</div>
    <div class=”post3″>Post3</div>
    <div class=”post4″>Post4</div>

    Is this possible?

Viewing 5 replies - 1 through 5 (of 5 total)
  • Thread Starter kevr1990

    (@kevr1990)

    Thanks for the link esmi. Unfortunately I can’t see anything on there to help – could you point it out?

    Apologies, although proficient at coding, I’m not an expert so need guiding a little at times.

    I can see the option to output the post ID as a class, but not the number in the list. So the most recent post would always be ‘post1’ regardless of its post id.

    If you use <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>> in your theme’s template files, each post will have its own unique id and class list. You an use these in your CSS to apply styling very specifically.

    :nth-child might come in handy
    https://nthmaster.com

    add a filter function to functions.php of your theme;
    https://codex.www.ads-software.com/Function_Reference/post_class#Add_Classes_By_Filters

    example:

    // add post number in post class
    	function post_number_class($classes) {
    	    global $wp_query;
    	        $classes[] = 'post' . ($wp_query->current_post+1);
    	        return $classes;
    	}
    	add_filter('post_class', 'post_number_class');

    alternatively, if your theme does not use post_class(), find the loop of your index template, and locate the post div; add the number there; example in a minimalistic loop:

    <?php if (have_posts()) :
       while (have_posts()) :
          the_post(); ?>
    <div class="post<?php echo $wp_query->current_post+1; ?>">
          <?php the_content(); ?>
    </div>
       <?php endwhile;
    endif; ?>
Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Query posts – numbers in class’ is closed to new replies.