How to Display wp_list_pages with a Dynamically Created Exclude List in WordPress

Home » Snippets » How to Display wp_list_pages with a Dynamically Created Exclude List in WordPress

Created with:



Creator: WPTurbo Team

Customize with WPTurbo AI

Add Snippet To Project

New Project
Add To Existing Project

Are you looking for a way to customize the display of your WordPress pages by excluding certain pages from the list? The wp_list_pages function is a convenient way to generate a list of your pages, but by default, it includes all pages on your site. In this article, we will show you how to dynamically create an exclude list for wp_list_pages so that you can have full control over which pages are displayed. Whether you want to hide specific pages from the navigation menu or create a custom page template without certain pages, this tutorial will provide you with the step-by-step instructions to achieve your desired result.

					function wpturbo_exclude_pages( $exclude ) {
    $dynamic_exclude = array( 2, 5, 7 );
    $exclude = implode( ',', $dynamic_exclude );
    return $exclude;
add_filter( 'wp_list_pages_excludes', 'wpturbo_exclude_pages', 10, 1 );

The code snippet provided is used to dynamically exclude specific pages from the wp_list_pages function in WordPress. With this code, you can easily create an exclude list and have it automatically applied to the wp_list_pages output.

The function wpturbo_exclude_pages() is defined to handle the exclusion process. Inside this function, we initialize an array called $dynamic_exclude that contains the page IDs we want to exclude from the list. For demonstration purposes, we have included page IDs 2, 5, and 7. You can modify this array and add or remove page IDs as needed.

Next, we use the implode() function to convert the array elements into a comma-separated string. This is necessary because the wp_list_pages function expects the $exclude parameter to be a comma-separated list of page IDs to exclude.

The final step in the function is to return the $exclude value. This value will be used by the wp_list_pages function to exclude the specified pages from the output.

To make this custom exclusion work, we need to hook our wpturbo_exclude_pages() function into the wp_list_pages_excludes filter. The add_filter() function is used for this purpose, with 'wp_list_pages_excludes' being the filter hook, 'wpturbo_exclude_pages' being the name of our custom function, and 10 being the priority (you can change it if needed). The 1 at the end specifies the number of arguments that our function accepts.

By using this code snippet and modifying the $dynamic_exclude array, you can easily exclude specific pages from the wp_list_pages function and have the changes automatically reflected whenever the function is called.

Register an account to save your snippets or go Pro to get more features.