Home > Mobile >  PHP Wordpress redirect if not mobile and ignore specific pages
PHP Wordpress redirect if not mobile and ignore specific pages

Time:10-28

I use the following code for redirecting non-mobile users to the desktop version of a website (a responsive theme is not an option), and it works perfectly until I need to access the WP Admin. How can I ignore the /wp-admin/ or wp-login.php page so I can still access the site if I am not already logged in?

if (!is_admin()) {
    if (!wp_is_mobile()) {
        // If not using mobile
        wp_redirect('https://my-desktop-site.com');
        exit;
    }
}

CodePudding user response:

is_admin determines whether the current request is for an administrative interface page.

In no cases whatsoever will it fire on a wp-login.php as it is NOT an admin screen. Tho it will indeed fire upon an ajax request, therefore that case should be handle. wp_doing_ajax() determines whether the current request is a WordPress Ajax request.

is_login() was recently announced for 6.1, tho, for the moment we still need to rely on $_SERVER["REQUEST_URI"].

<?php

add_action( 'template_redirect', function () {

    $request_uri = filter_input( INPUT_SERVER, 'REQUEST_URI', FILTER_SANITIZE_STRING );

    if ( ! is_admin() && ! str_contains( basename( $request_uri ), 'wp-login.php' ) ) {

        if ( ! wp_is_mobile() ) {

            wp_redirect( 'https://...' );

            exit;

        }
    };

} );
  • Related