Dynamic redirects

tdrayson

I was rebuilding my podcast website that I co-host with my Dad and something we wanted to do was add a dynamic link in the header that redirected to the latest episode.

Updated 25/05/2023: I have found a new method which works with the URL path and doesn't rely on query params

URL Path Method

This updated method allows you to redirect based on full URL paths.

For example /latest could redirect to your latest post. If you vist https://snippetclub.com/latest, it will take you to my most recent tutorial.

PHP

        /*
 * tct_dynamic_redirects
 *
 * @function Redirects user dynamically using PHP
 * @author Taylor Drayson
 * @since 25/05/2023
*/
add_action('template_redirect', 'tct_dynamic_redirects');
function tct_dynamic_redirects() {
    // Get the current URL
    $current_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    
    // Extract the path from the URL
    $path = parse_url($current_url, PHP_URL_PATH);

    // Handle redirect
    $redirect = tct_handle_redirects($path);
    
    if($redirect === null) return;
    
    wp_redirect($redirect, 301);
    exit;
}

function tct_handle_redirects($path){

    $url = null;
    $path = strtolower($path);
    $path = rtrim($path,"/");

    switch ($path) {
        case '/latest':
            $latest = get_posts(['post_type' => 'post', 'posts_per_page' => 1, 'no_found_rows' => true]);
            $url = get_permalink($latest[0]);
            break;
        case '/personal':
            $url = 'https://taylordrayson.com';
            break;
        case '/company':
            $url = 'https://thecreativetinker.com';
            break;
    }

    return $url;
}
      
Copy

Code breakdown

There are 2 parts to this snippet, the main redirect function tct_dynamic_redirects and tct_handle_redirects

The first function is where we get the requested path the user has visited. We then pass it into the our handle function where we can write all of our routes for different urls. You can have any path that you like including multiple slashes.

For example

  • /latest/post
  • /latest/event

These could be nice if you have multiple post types.

In our switch statement with check for the $path. If there is a match, we can then set the $url variable to the absolute or relative url we want to redirect to.

You could also use your own function if you want to do more complex calculations to determine the url without making your handle redirect function messy.

Note: Query params will not be used or passed through to the target url.

Query Param Method

The solution I settled on was using query params in the url:

https://domain.com/?go=latest-episode

I then use the template_redirect function to hook into the page before it has a chance to load the page and then use wp_redirect and some php logic to redirect to the correct place.

The snippet

Copy and paste the code below into functions.php or code snippet plugin.

PHP

        /*
 * tct_dynamic_redirects
 *
 * @function Dynamic query string redirects
 * @author Taylor Drayson
 * @since 29/12/2022
 */

function tct_dynamic_redirects()
{
    if (isset($_GET["go"])) {
        $type = $_GET["go"];
        $url = "";

        switch ($type) {
            case 'latest-episode':
                $latest = get_posts(['post_type' => 'post', 'posts_per_page' => 1, 'no_found_rows' => true]);
                $url = get_permalink($latest[0]);
                break;
        }

        if ( !empty( $url ) ) {
            wp_redirect($url);
            exit();
        }
    }
}
add_action("template_redirect", "tct_dynamic_redirects");
      
Copy

I am using a switch case, this allows me to easily add more dynamic redirects against different params values.

In your switch statements, set $url to the place you want to redirect to.

👋🏻 Weekly Tutorial Digest

I send out a weekly newsletter with links to new tutorials written in the last week, you can subscribe below.

Newsletter

🔒I won't send you spam, I promise