Add Snippet To Project
If you’re managing a WordPress website with multiple pages, you might find it challenging to keep them organized in a logical order. Fortunately, WordPress makes it easy to rearrange your pages. In this article, we’ll walk you through how to rearrange your pages in WordPress using the built-in page editor and a plugin. Whether you need to change the order of your pages for navigation purposes or for SEO reasons, this guide has got you covered.
function wpturbo_rearrange_pages($query) {
if ($query->is_main_query() && is_admin()) {
if (isset($_GET['post_type']) && $_GET['post_type'] == 'page') {
$query->set('orderby', 'menu_order');
$query->set('order', 'ASC');
}
}
}
add_action('pre_get_posts', 'wpturbo_rearrange_pages');
The code snippet provided above can help you rearrange pages in WordPress. To understand how it works, let’s break it down step by step.
Firstly, we define a function called wpturbo_rearrange_pages()
. This function takes in the $query
object and checks if the current query is the main query and if we are in the admin area of WordPress.
if ($query->is_main_query() && is_admin()) {
This ensures that the code only executes when we are in the admin area of WordPress.
Next, we check to see if the current query is for the page
post type by checking if the post_type
query parameter is set to page
.
if (isset($_GET['post_type']) && $_GET['post_type'] == 'page') {
If the query is for the page
post type, we append orderby
and order
arguments to the $query
object to rearrange the pages based on their menu order.
$query->set('orderby', 'menu_order');
$query->set('order', 'ASC');
This means that the pages will be displayed in ascending order based on their menu order. Of course, you can change the value of order
to DESC
if you want to display the pages in descending order.
Finally, we use the add_action()
function to attach our wpturbo_rearrange_pages()
function to the pre_get_posts
action.
add_action('pre_get_posts', 'wpturbo_rearrange_pages');
This ensures that our code is executed early enough in the WordPress query process for the orderby
and order
arguments to take effect.
That’s it! By adding this code snippet to your WordPress site, you can easily rearrange pages based on their menu order.