First of all, this isn't my code and I've received a lot of help in getting it to this stage. My problem is this: the random redirect works perfectly once, and if you click around the site for a while or clear your browsing history, it will work again. So it's as if the rng generates a random page once but then remembers that page and links back to it each time after.
As you'll see below, a link goes to a dummy page called "random page" which then redirects to a random page on the site (excluding a number of pages listed on line 5). The issue seems to be that the seed for the rng isn't resetting. I've been working with my software engineer neighbor and we've tried all kinds of things but nothing has worked. For one thing, we tried changing array_rand on line 7 to mt_rand, but this caused a "too many redirects" error.
The original code is this:
add_action('template_redirect', 'wpsf_random_page_redirect');
function wpsf_random_page_redirect()
{
if (is_page('random-page')) {
$excluded_pages = array(125, 126, 508, 510, 723, 987, 995, 1079, 1109, 1121, 1135, 1146, 1159, 1177, 1188, 1418, 1433);
$pages = get_pages(array('exclude' => $excluded_pages));
$random_page = $pages[array_rand($pages)];
$page_url = get_page_link($random_page);
wp_redirect($page_url);
exit;
}
}
We've tried adding a second dummy page, adding srand(); into the code or various locations such as the dummy page meta description, and much more. Our closest attempt to a solution, we think, was changing array_rand to mt_rand and getting the too many redirects error.
I've looked all around the web and couldn't figure it out (partly because all this is mostly gibberish to me), but neither could my neighbor it seems, and he knows what he's doing. Any ideas would be much appreciated, thanks!
CodePudding user response:
It might be a caching issue so try adding nocache_headers();
like so
add_action('template_redirect', 'wpsf_random_page_redirect');
function wpsf_random_page_redirect()
{
if (is_page('random-page')) {
$excluded_pages = array(125, 126, 508, 510, 723, 987, 995, 1079, 1109, 1121, 1135, 1146, 1159, 1177, 1188, 1418, 1433);
$pages = get_pages(array('exclude' => $excluded_pages));
$random_page = $pages[array_rand($pages)];
$page_url = get_page_link($random_page);
nocache_headers();
wp_redirect($page_url);
exit;
}
}