Skip to content

Instantly share code, notes, and snippets.

@brandonbarringer
Last active October 18, 2022 16:25
Show Gist options
  • Save brandonbarringer/be4e2807c22075c281138cf04ad7b245 to your computer and use it in GitHub Desktop.
Save brandonbarringer/be4e2807c22075c281138cf04ad7b245 to your computer and use it in GitHub Desktop.
Get Related Pages Based on Menu Hierarchy in WordPress
<?php
function getRelatedPages($pageID, $limit = 10) {
// if this page has a parent, query for sybling pages
// else if this page is a parent, query for child pages
// else query for other top level pages
$parentID = wp_get_post_parent_id(get_the_ID());
$pages = [];
if ($parentID) {
$pages = Helpers::getPagesHierarchy([
'sort_column' => 'menu_order',
'child_of' => $parentID,
'echo' => false
]);
} else {
$pages = Helpers::getPagesHierarchy([
'sort_column' => 'menu_order',
'parent' => get_the_ID(),
'echo' => false
]);
}
if (!$pages) {
$pages = Helpers::getPagesHierarchy([
'sort_column' => 'menu_order',
'parent' => 0,
'echo' => false
]);
}
$pages = array_filter($pages, function($page) {
return $page->ID !== get_the_ID();
});
$pages = array_slice($pages, 0, $limit);
// if there are less than $limit pages, fill the rest with random pages not in the list
if (count($pages) < $limit) {
$randomPages = Helpers::getPagesHierarchy([
'sort_column' => 'menu_order',
'parent' => 0,
'echo' => false
]);
$randomPages = array_filter($randomPages, function($page) use ($pages) {
return $page->ID !== get_the_ID() && !in_array($page->ID, array_map(function($page) {
return $page->ID;
}, $pages));
});
shuffle($randomPages);
$pages = array_merge($pages, array_slice($randomPages, 0, $limit - count($pages)));
}
return $pages;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment