Custom Cookie-Based User Redirect Using WP_Http_Cookie

Last updated 1 month ago

PHP
function set_last_category_visited_cookie() {
    if (is_category()) {
        $category = get_queried_object();
        $cookie = new WP_Http_Cookie(array(
            'name'     => 'last_category_visited',
            'value'    => $category->slug,
            'expires'  => time() + MONTH_IN_SECONDS,
            'path'     => '/',
        ));

        // Set the cookie for the user.
        wp_remote_get(home_url(), array('cookies' => array($cookie)));
    }
}

add_action('template_redirect', 'set_last_category_visited_cookie');

function redirect_to_last_category_visited() {
    if (isset($_COOKIE['last_category_visited']) && !is_category()) {
        $last_category_slug = sanitize_text_field($_COOKIE['last_category_visited']);
        wp_safe_redirect(get_category_link(get_category_by_slug($last_category_slug)->term_id));
        exit;
    }
}

add_action('init', 'redirect_to_last_category_visited');

All code snippets are licensed GPLv2 or later unless otherwise stated.