Skip to content

Instantly share code, notes, and snippets.

@wpsmithtwc
Last active April 21, 2017 21:50
Show Gist options
  • Save wpsmithtwc/375415a9dd1d4d1034347b0ca4a0c5fb to your computer and use it in GitHub Desktop.
Save wpsmithtwc/375415a9dd1d4d1034347b0ca4a0c5fb to your computer and use it in GitHub Desktop.
<?php
/**
* Outputs the state link.
*
* @param $articles array Array of articles array('url'=>'', 'title'=> '',)
* @param $state string State name.
*/
function do_state( $articles, $state ) {
if ( isset( $articles[ $state ] ) ) {
// do state link open
   printf('<li><div class="state-link">%s</div><ul class="article-list">', $state );
// do articles
   foreach ( $articles[ $state ] as $article ) {
     do_state_article( $article );
}
// close state link
echo '</ul></li>';
 } else {
// do nada
   printf( '<div class="inactive state-link">%s</div>', $state );
 }
}
/**
* Outputs the state article link
*
* @param $artcle array Article array.
*/
function do_state_article( $article ) {
printf( '<li class="article-list-item"><a class="article-link" href="%s">%s</a></li>', $article['url'], $article['title'] );
}
<?php
$_terms = get_terms( array( 'state' ) );
 $articles = array();
 foreach ((array)$_terms as $term):
     $_posts = new WP_Query( array(
      'post_type'         => 'page',
       'posts_per_page'    => 10, //important for a PHP memory limit warning
       'tax_query' => array(
        array(
          'taxonomy' => 'state',
           'field'    => 'slug',
           'terms'    => $term->slug,
         ),
       ),
     ) );
     if( $_posts->have_posts() ) :
$articles[$term_name] = array();
       while ( $_posts->have_posts() ) : $_posts->the_post();
$articles[$term_name][] = array(
      'title' => get_the_title(),
       'url' => get_permalink(),
      );
       endwhile;
     endif;
     wp_reset_postdata();
 endforeach;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment