WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] List posts grouped by first letter of title (3 posts)

  1. leemon
    Member
    Posted 1 year ago #

    Hi!

    I'm using the following piece of code to list posts grouped by the first letter of their title:

    $posts = get_posts( $args );
    foreach( $posts as $post ) {
        $this_char = strtoupper(mb_substr($post->post_title, 0, 1, 'UTF-8'));
        if ($this_char != $last_char) {
            if ($last_char != '') {
                $html .= '</ul>';
                $html .= '</div>';
            }
            $last_char = $this_char;
            $html .= '<div class="letter">';
            $html .= '<h2>'.$last_char.'</h2>';
            $html .= '<ul>';
            $html .= '<li><a href="'.get_permalink($post->ID).'">'.$post->post_title.'</a></li>';
        } else {
            $html .= '<li><a href="'.get_permalink($post->ID).'">'.$post->post_title.'</a></li>';
        }
    }
    $html .= '</ul>';
    $html .= '</div>';

    I'm wondering if there's a way to group the posts starting with 0,1,2,3,4,5,6,7,8 or 9 in an unique group called "number".

    Thanks in advance

  2. vtxyzzy
    Member
    Posted 1 year ago #

    You should be able to do this by changing this:

    $this_char = strtoupper(mb_substr($post->post_title, 0, 1, 'UTF-8'));
        if ($this_char != $last_char) {

    to this (UNTESTED):

    $this_char = strtoupper(mb_substr($post->post_title, 0, 1, 'UTF-8'));
    if (strpos('0123456789',$this_char) !== false) $this_char = '0-9';
    if ($this_char != $last_char) {
  3. leemon
    Member
    Posted 1 year ago #

    It works!

    Thanks!!!

Topic Closed

This topic has been closed to new replies.

About this Topic