Ace Goulet

Redirect Interface for WordPress Admin

Lots of sites end up needing a client-friendly interface for creating url redirects. Previously the main way I would create a wordpress interface for vanity urls was to have a custom page template for redirects with a custom field for destination url, and the vanity url would be the slug of the page. This is a little clunky in that you can end up with a ton of pages that do nothing besides redirect users.

So I put togther another way of doing it that’s more user-friendly.

First created an options page with ACF with a repeater field that has two fields (vanity & destination):

If you haven’t ever user options pages in ACF, check out the docs here: http://www.advancedcustomfields.com/add-ons/options-page/

Then I put together a function that runs at the top of the theme header.php file and only fires if wordpress is about to serve up the 404 page (this is to prevent them from redirecting an existing piece of published content accidentally).

function url_redirects(){
     //check if this is a 404
     if(is_404()){
          $url = $_SERVER['REQUEST_URI'];
          $url_path = parse_url($url, PHP_URL_PATH);
          $redirects_array = get_field('redirects', 'option');
          foreach($redirects_array as $redirect) {
               if($redirect['vanity_url_slug'] == $url_path){
                    header( 'Location: ' . $redirect['destination_url'] ) ;
               }
          }
     }
}
Exit mobile version