Advertisement
SimeonGriggs

Sort and Group Posts by Custom Field with Unique Headings in

Sep 30th, 2015
851
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.24 KB | None | 0 0
  1. <?php
  2.     $args = array(
  3.         'post_type' => 'branch',
  4.         'numberposts' => -1,
  5.         'order' => 'ASC',
  6.         'orderby' => 'meta_value',
  7.         'meta_key' => 'state',
  8.     );
  9.  
  10.     $branch_posts = get_posts($args);
  11.     foreach($branch_posts as $post) :
  12.     setup_postdata( $post );
  13.                        
  14. ?>
  15.    
  16.     <?php
  17.         // Only show posts with the 'State' custom field
  18.         if (get_field('state')) {
  19.        
  20.             // Set the state of this post
  21.             $current_state = get_field('state');
  22.  
  23.             // If this post doesn't have the same 'State' as the last one, let's give this one a heading and open the <ul>
  24.             if ($current_state != $previous_state) {
  25.                
  26.             // $previous_state isn't set until the end of this foreach, so the first one doesn't have this variable
  27.             // If this isn't the first list, close the last list's <ul>
  28.             if ($previous_state) { echo '</ul>'; }
  29.         ?>
  30.            
  31.             <h1><strong><?php echo $current_state; ?></strong></h1>
  32.             <ul>
  33.                
  34.         <?php } ?>
  35.        
  36.                 <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>                      
  37.                    
  38.         <?php
  39.             // Remember, we closed the <ul> before the <li>'s, clever huh?
  40.            
  41.             // Set the 'State' of the this post, to compare to the next post
  42.             $previous_state = get_field('state');
  43.     } ?>
  44. <?php endforeach; wp_reset_postdata(); ?>
  45. </ul>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement