Last active
December 17, 2019 06:06
-
-
Save samikeijonen/405c290caccb923522f155de44644b35 to your computer and use it in GitHub Desktop.
Display posts by alphabetical order in a way that first letter of each name is presented.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Display 'attendee' post type in alphabetical order by it's category. | |
* | |
* The output looks like this: | |
* | |
* A | |
* Ace Bill | |
* Alb Nick | |
* | |
* B | |
* Bell Evin | |
* | |
* C | |
* Carllson Carla | |
* Cure Sam | |
* | |
* @since 1.0.0 | |
* @author Done by help of Justin Tadlock. themehybrid.com. | |
* @param array $atts The attributes to pass to the shortcode | |
* @param string $content The content of the shortcode | |
* @return string $attendees_list The data to return for the shortcode | |
*/ | |
function prefix_features_attendees_shortcode( $atts, $content = null ) { | |
$atts = shortcode_atts( array( | |
'category' => null, | |
), $atts ); | |
// Bail if there is no attendee category. | |
if ( null === $atts['category'] ) { | |
return; | |
} | |
// Set sorted array. | |
$sorted = array(); | |
// Set args for getting attendees list. | |
$attendees_args = array( | |
'numberposts' => 500, | |
'tax_query' => array( | |
array( | |
'taxonomy' => 'attendee-category', | |
'field' => 'slug', | |
'terms' => esc_attr( $atts['category'] ), | |
), | |
), | |
'orderby' => 'title', | |
'order' => 'DESC', | |
'post_type' => 'attendee', | |
); | |
// Get attendees 'posts'. | |
$posts = get_posts( $attendees_args ); | |
// Loop attendees list and add post title. | |
foreach ( $posts as $post ) { | |
setup_postdata( $post ); | |
$name = strtolower( $post->post_title ); | |
$char = $name[0]; | |
if ( ! isset( $sorted[ $char ] ) ) { | |
$sorted[ $char ] = array(); | |
} | |
$sorted[ $char ][] = $post->post_title; // Or, whatever you want to output. | |
} | |
// Sort alphabetically by character. | |
ksort( $sorted ); | |
// Set attendees list which we return. | |
$attendees_list = ''; | |
// Loop through the sorted character. | |
foreach ( $sorted as $character => $attendees ) { | |
// Get first letter (A, B, C, or D and so on). | |
$attendees_list .= '<span class="attendees-first-letter">' . $character . '</span></br>'; | |
// Loop through each post for the character. | |
$attendees_list .= '<ul class="attendees-list">'; | |
foreach ( $attendees as $attendee ) { | |
$attendees_list .= '<li>' . $attendee . '</li>'; | |
} | |
$attendees_list .= '</ul>'; | |
} | |
// Reset post data. | |
wp_reset_postdata(); | |
// Return attendee list. | |
return $attendees_list; | |
} | |
add_shortcode( 'attendees', 'prefix_features_attendees_shortcode' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment