How to create a function to add css class for each first word with same letter from which it starts?

Tags: , ,



I did a list and search field on WordPress. Search type works with post-types. I need to create a function, which should add my css class with Letter. It should be like on screenshot. It should looks like here

My Code to show this list:

                <form class="antibodies-form" action="">
                    <input type="text" name="keyword" id="keyword" onkeyup="fetch()"
                           placeholder="Search our Research Antibodies "></input>
                </form>

                <h3 class="antibodies-title">Research Antibodies</h3>
                <ul id="datafetch" class="antibodies-items">
                    <?php
                    $the_query = new WP_Query(array('posts_per_page' => -1, 's' => esc_attr($_POST['keyword']), 'post_type' => 'antibodies'));
                    if ($the_query->have_posts()) :
                        while ($the_query->have_posts()): $the_query->the_post(); ?>

                            <li><a href="<?php echo esc_url(post_permalink()); ?>"><?php the_title(); ?></a></li>

                        <?php endwhile;
                        wp_reset_postdata();
                    endif;

                    ?>

My span element with specific class which will add this letter: It should be inside

  • element.
    <span class="antibodies-item-letter">A</span>
    
  • Answer

    You can set an empty variable as the current index and then loop through your posts. On each iteration you can get the first character of the title via substr( get_the_title(), 0, 1 ).

    If the current index does not match the first character, make the current index equal to the first character and add an extra span to the <li> containing the current index.

    $the_query = new WP_Query( array(
        'posts_per_page'    => -1, 
        'post_type'         => 'antibodies',
        'order'             => 'ASC', 
        'orderby'           => 'title',
        's'                 => esc_attr( $_POST['keyword'] ),
    ));
    if ( $the_query->have_posts() ) {
        $current_index = '';
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            $first_char = substr( get_the_title(), 0, 1 );
            if ( $current_index !== $first_char ) {
                $current_index = $first_char;
                printf( '<li><span class="antibodies-item-letter">%s</span><a href="%s">%s</a></li>', $current_index, get_permalink(), get_the_title() );
            } else {
                printf( '<li><a href="%s">%s</a></li>', get_permalink(), get_the_title() );
            }
        }
        wp_reset_postdata();
    }
    


    Source: stackoverflow