Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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