Dynamic redirects

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.

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.


            /*
 * 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.

🔒I won't send you spam, I promise