Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Show posts group by alphabet with shortcode `prefix_alphabetic_posts`. Note: function `prefix_get_posts_group_by_alphabet()` is added in gist https://gist.github.com/d1fd806d39a02220bc3c5d372919c100
<?php
add_shortcode( 'prefix_alphabetic_posts', 'prefix_alphabetic_posts' );
function prefix_alphabetic_posts() {
ob_start();
?>
<style type="text/css">
#alphabetical-posts .letters li {
display: inline-block;
margin: 0;
}
#alphabetical-posts .letters a {
text-decoration: none;
font-size: 16px;
background: #ffffff;
height: 2em;
display: inline-block;
width: 2em;
line-height: 2em;
color: #2196F3;
margin: 0;
}
#alphabetical-posts .letters {
text-align: center;
display: inline-flex;
}
#alphabetical-posts .letters-wrap {
text-align: center;
}
#alphabetical-posts .letters a:hover {
background: #2196F3;
color: #fff;
}
#alphabetical-posts .posts {
margin-top: 4em;
max-width: 900px;
margin: 0 auto;
}
#alphabetical-posts .posts .item {
margin-bottom: 4em;
}
#alphabetical-posts .posts .item a {
text-decoration: none;
font-size: 14px;
}
#alphabetical-posts .posts .list > div {
background: #fff;
padding: 15px 15px;
border-bottom: 1px solid #f2f2f2;
}
#alphabetical-posts .list h3 {
margin: 0;
}
#alphabetical-posts .list .content {
margin-top: 5px;
}
</style>
<?php
$result = prefix_get_posts_group_by_alphabet();
if( $result ) { ?>
<div id="alphabetical-posts">
<?php $letters = array_keys($result); ?>
<?php if( $letters ) { ?>
<div class="letters-wrap">
<ul class="letters">
<?php foreach( $letters as $key => $letter ) { ?>
<li><a href="#goto-letter-<?php echo $letter; ?>"><?php echo $letter; ?></a></li>
<?php } ?>
</ul>
</div>
<?php } ?>
<div class="posts">
<?php foreach( $result as $letter => $posts ) { ?>
<div id="goto-letter-<?php echo $letter; ?>" class="item">
<h3><?php echo $letter; ?></h3>
<div class="list">
<?php foreach( $posts as $key => $post ) { ?>
<div>
<h3><a href="#"><?php echo $post['title']; ?></a></h3>
<div class="content">
<?php echo wp_trim_words( get_the_excerpt( $post['ID'] ), 20 ); ?>
</div>
</div>
<?php } ?>
</div>
</div>
<?php } ?>
</div>
</div>
<?php }
return ob_get_clean();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment