Add Snippet To Project
Ever wondered how you could get an overview of all the pages on your WordPress website? Or perhaps you need to reorder the pages for your site menu? In WordPress, there’s a simple way to list all the pages with just a few clicks. In this article, we’ll guide you through the process of listing all pages on your WordPress website, both from the admin panel and programmatically. This makes it easy to manage and maintain your site structure, give it a visual refresh, or just get a good sense at a glance of what’s present on your site.
function wpturbo_list_pages() {
$args = array(
'post_type' => 'page',
'post_status' => 'publish'
);
$pages = get_posts( $args );
echo '<ul class="wpturbo-page-list">';
foreach ( $pages as $page ) {
echo '<li><a href="' . get_the_permalink($page->ID) . '">' . get_the_title($page->ID) . '</a></li>';
}
echo '</ul>';
}
add_action( 'init', 'wpturbo_list_pages' );
The first portion of the code snippet is defining a function known as wpturbo_list_pages()
. This function contains logic that retrieves all WordPress pages that have been published on your site.
$args = array(
'post_type' => 'page',
'post_status' => 'publish'
);
This part of the function is setting up an array of arguments. The ‘post_type’ => ‘page’ specifies that we want to retrieve WordPress pages in particular (not posts or any other custom post types). The ‘post_status’ => ‘publish’ ensures that only pages that have been published will be retrieved.
Following, the function uses the get_posts
WordPress function which uses the arguments from $args
to make a database query.
$pages = get_posts( $args );
The result of get_posts
will be an array of objects, with each object containing data about a specific page. This array is stored in the variable $pages
.
Then, it begins outputting a list by echoing an opening <ul>
HTML tag with the class wpturbo-page-list
.
echo '<ul class="wpturbo-page-list">';
The foreach
loop that follows iterates through each published page stored in the $pages
array.
foreach ( $pages as $page ) {
echo '<li><a href="' . get_the_permalink($page->ID) . '">' . get_the_title($page->ID) . '</a></li>';
}
For each page, it’s creating a list item <li>
that outputs a hyperlink <a>
, which has the URL of the page (retrieved using the WordPress function get_the_permalink
), and the page title as the link text (retrieved using the WordPress function get_the_title
).
After our foreach
loop has finished, it closes our unordered list by echoing the closing </ul>
.
echo '</ul>';
Finally, add_action( 'init', 'wpturbo_list_pages' );
is used at the end, this piece of code ensures that the function wpturbo_list_pages()
is executed at the init
hook which is one of the earliest hooks available in WordPress.