How can I get the first 50% of all posts (within a custom post type)?

I’m trying to make a multi column layout. Seen as CSS3 adoption of column layouts is still thin on the ground, I was thinking maybe I could grab the first half of all my posts (and then the second), and add them in their own UL elements.

I’m not sure how / if this is possible with a Wp_Query?

Read More

I want to end up with my posts in alphabetical order, but split into two lists (using two queries, I guess), thus:

<ul>
<li>a</li>
.
.
.
</li>m</li>
</ul>
<ul>
<li>n</li>
.
.
.
</li>z</li>
</ul>

I could then style each list with CSS and get a layout kind of like a multi column layout in CSS3.

Does anyone have any ideas about how to structure my queries here?

edit to explain how this isn’t a duplicate

It’s about forming a two column layout sure, but the question is very different: ‘how to get half of all posts’, not how to solve a very specific layout use case as is the linked ‘duplicate’. (which I didn’t find on account of it not being the same question).

Further, I was looking for posts sorted alphabetically, vertically descending, not A|B, C|D as in the example.

Related posts

2 comments

  1. If you want to split it into two lists, you could use wp_count_posts() to count the number of your published posts

    $total_cpt = wp_count_posts('cpt')->publish;
    

    divide it by 2:

    $half_of_cpt = sprintf( '%d', $total_cpt / 2 );
    

    and then you could use this number in the loop to split your list.

  2. The following

    • will work for every query (even with pagination), so it’s more flexible
    • need only one loop (as the best implementation of wp_count_posts)
    • don’t call other additional db query like wp_count_posts do, so it’s faster
    • do not need any other variable ouside loop, so it’s simpler

      $args = array('post_type'=>'cpt', 'orderby'=>'title', 'order'=>'ASC'); // any args here
      $query = new WP_Query($args);
      
      if ( $query->have_posts() ) :
        echo '<ul>';
        while ( $query->have_posts() ) : $query->the_post();
      
          echo '<li>' . get_the_title() . '</li>';
          if ( ( $query->current_post + 1 ) == ceil($query->post_count / 2) ) echo '</ul><ul>';
      
        endwhile;
        echo '</ul>';
      endif;
      

Comments are closed.