Skip to content

Instantly share code, notes, and snippets.

@GavinJaynes
Created June 6, 2014 10:53
Show Gist options
  • Save GavinJaynes/261cc588ae7e352945bb to your computer and use it in GitHub Desktop.
Save GavinJaynes/261cc588ae7e352945bb to your computer and use it in GitHub Desktop.
A WordPress redirect function where you can redirect using slugs or full urls. It also takes in an exceptions as an array of slugs.
<?php
// ====================================================
// -- HANDY REDIRECT FUNCTION
// -- Takes in 2 param:
// -- 1. String: slug and parent eg: parent-page/child-page/
// -- 2. Boolean: if it's just the slug or the full url
// -- 3. Array of strings: Any Exceptions
// ====================================================
function go_to( $destination, $full_url, $exceptions ) {
$current_url = home_url(add_query_arg(array()));
$slug = basename($destination);
array_push($exceptions, $slug);
$allowed_pages = strposa($current_url, $exceptions);
if ( $allowed_pages === false) {
if($full_url) {
wp_redirect( $destination );
exit;
} else {
wp_redirect( home_url() .'/'. $slug );
exit;
}
}
}
// ====================================================
// -- HANDY FUNCTION TO STRPOS THROUGH AN ARRAY
// ====================================================
function strposa($haystack, $needles = array())
{
$result = array();
foreach($needles as $needle)
{
$res = strpos($haystack, $needle);
if ($res !== false) $result[$needle] = $res;
}
if(empty($result)) return false;
return min($result);
}
// ======= BUFFER THE OUTPUT FOR REDIRECTS ========
// ================================================
function app_output_buffer() {
ob_start();
}
add_action('init', 'app_output_buffer');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment