sinanisler logo

Get Latest Pages Parent Child in Order, WordPress Shortcode, List

This code adds [page_link_list] shortcode.  and gets the latest pages in the current page. current page child parent pages

It will not just get the latest pages but it wil lget them in ul li order and it will make the parent and child ordering with ul li sub ul under li too.

You can customize with css however you like.

function page_link_list_shortcode() {
    global $post;
    $current_page_id = get_the_ID(); // Get the ID of the current page

    // Filter for adding 'current' class to child pages
    add_filter('wp_list_pages', function ($output) use ($current_page_id) {
        if (is_page() && strpos($output, 'page-item-' . $current_page_id) !== false) {
            $output = preg_replace('/page-item-' . $current_page_id . '"><a/', 'page-item-' . $current_page_id . '"><a class="current"', $output);
        }
        return $output;
    });

    $args = array(
        'post_type'      => 'page',
        'posts_per_page' => 100,
        'post_status'    => 'publish',
        'sort_column'    => 'menu_order, post_title',
        'echo'           => 0,
    );

    $pages = get_pages($args);
    $output = '<ul>';

    foreach ($pages as $page) {
        // Check if it's a top-level page
        if ($page->post_parent == 0) {
            $class = ($page->ID == $current_page_id) ? ' class="current"' : '';

            $output .= '<li><a href="' . get_page_link($page->ID) . '"' . $class . '>' . get_the_title($page->ID) . '</a>';

            // Fetch and format child pages
            $child_pages = wp_list_pages(array(
                'title_li'    => '',
                'child_of'    => $page->ID,
                'echo'        => 0,
                'post_type'   => 'page',
                'sort_column' => 'menu_order, post_title'
            ));

            if ($child_pages) {
                $output .= '<ul>' . $child_pages . '</ul>';
            }

            $output .= '</li>';
        }
    }

    $output .= '</ul>';
    return $output;
}
add_shortcode('page_link_list', 'page_link_list_shortcode');


something similar like this;

Leave the first comment