Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@maheshwaghmare
Last active August 6, 2019 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maheshwaghmare/d1fd806d39a02220bc3c5d372919c100 to your computer and use it in GitHub Desktop.
Save maheshwaghmare/d1fd806d39a02220bc3c5d372919c100 to your computer and use it in GitHub Desktop.
Get posts group by alphabets and show it with shortcode.
<?php
/**
* Get posts group by alphabets.
*
* @todo Change the `prefix_` and with your own unique prefix.
*
* @since 1.0.0
*/
if( ! function_exists( 'prefix_get_posts_group_by_alphabet' ) ) :
function prefix_get_posts_group_by_alphabet() {
$result = array();
$query_args = array(
'post_type' => 'post',
// Query performance optimization.
'no_found_rows' => true,
'posts_per_page' => 100,
);
$query = new WP_Query( $query_args );
if ( $query->posts ) {
foreach ( $query->posts as $key => $post ) {
$first_letter = substr($post->post_title,0,1);
if( ! empty( $first_letter ) ) {
$result[$first_letter][] = array(
'ID' => $post->ID,
'title' => $post->post_title,
);
}
}
}
if( ! empty( $result ) ) {
ksort( $result );
}
return $result;
}
endif;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment