How can I create a function to show child pages alphabetically? (WordPress)

What I’m trying to do is create a dictionary page listing alphbaticlly child pages of the main dictionary page, this is working however only for the first two letters, and after that it stops, I can’t seem to figure out why.

Here is my code:

        <?php

    $my_wp_query = new WP_Query();
    $all_wp_pages = $my_wp_query->query(array('post_type' => 'page', 'orderby' => 'title', 'order' => 'ASC'));

    $children = get_page_children($post->ID, $all_wp_pages);

    $letter="";
    foreach ($children as $child)
    {
        $first_letter=strtoupper(substr($child->post_title,0,1));
        if($letter != $first_letter)
        {
            $alphabetic[]->post_title=$first_letter;
            $letter=$first_letter;
        }
        $alphabetic[]=$child;
    }

        $col = 1; //how many columns

        for($i = 0; $i < $col; $i++) {


                $nr = (int)(sizeof($alphabetic)/4);
                $i == $col - 1 ? $end = sizeof($alphabetic) : $end = $nr*($i+1);

                echo '<div>';

                for($j = $nr*$i; $j < $end; $j++) {
                    if(strlen($alphabetic[$j]->post_title)==1)
                        echo '</div><div class="dict-cell"><div class="dict-letter">', $alphabetic[$j]->post_title, '</div>';
                    else
                        echo '<div class="dict-term"><a href="'.get_permalink($alphabetic[$j]->ID).'">'.$alphabetic[$j]->post_title.'</a></div>';
                }

            echo '</div>';

        } ?>

Related posts

2 comments

  1. You have just to use “SORT_REGULAR” for you type of sort

    sort($..->post_title)
    
  2. If anyone is ever trying to do the same thing I got that figured out in a different way which works perfectly for me.

    What my code does is running a loop over the alphabets and if there is a child page of specific ID it will print the First letter and then list all the child pages with the same first letter, that way you can create a glossary of pages.

    The code if also made so if there is no child pages under some letters they won’t show so you don’t get a list of empty letters as headings for no reason.

        <?php
        for ($letter = 'A'; $letter != 'AA'; $letter++) {
        $child_pages = $wpdb->get_results("SELECT *  FROM $wpdb->posts WHERE post_title like '$letter%' AND post_parent = '2523' AND post_status='publish'");
            if ( $child_pages ) { ?>
    
                <div class="dict-cell">
                    <div class="dict-letter">
                        <?php echo $letter; ?>
                    </div>
    
            <?php foreach ( $child_pages as $pageChild ) { ?>
                <div class="dict-term">
                    <a href="<?php echo get_permalink($pageChild->ID); ?>" rel="bookmark"><?php echo $pageChild->post_title; ?></a>
                </div>
    
         <?php } echo '</div>';  } } ?>
    

Comments are closed.