GavinJaynes
6/6/2014 - 10:53 AM

A WordPress redirect function where you can redirect using slugs or full urls. It also takes in an exceptions as an array of slugs.

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');