skip to Main Content

I’m looking for code that will detect if the user is on a desktop, then give them 404 error.

For example:
If a desktop user visit example.com/loreupsum then give them a 404 error, but bots and mobile users get the URL contain (the actual page).

I found this code:

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} ^.*(MSIE.*Windows NT|Lynx|Safari|Opera|Firefox|Konqueror) [NC]
RewriteRule ^(loreupsum)$ [L,R=404]

But this give the 404 error to all the users.

2

Answers


  1. Chosen as BEST ANSWER

    This can be acheive using wp_is_mobile() that looks at the $_SERVER['HTTP_USER_AGENT'] to determine whether we're in a mobile context.

    Here is a basic page template example (give_404.php) which is on the theme diretory:

    <?php
    
    /**
     * Template Name: Mobile restricted page
     *
     * @since 1.0.0
     */
    if ( ! wp_is_mobile() ) {
    
        global $wp_query;
    
        $wp_query->set_404();
    
        status_header( 404 );
    
        get_template_part( 404 );
    
        exit();
    
    };
    
    get_header();
    
    //...
    
    get_footer();
    

    then trigger the above template using add-action for the specfic url you want to give 404 to desktop users from fucntions.php of the theme:

    add_action('wp', function() {
    if ( trim(parse_url(add_query_arg(array()), PHP_URL_PATH), '/') === 'pagename' ) {
    include(locate_template('give_404.php'));
    exit();
    }});
    

    But how one can do it for multiple URLs. Is it possible to made a file suppose block_url.txt? That has all the url for which above template triggers.


  2. You could use wp_is_mobile() which is looking at the $_SERVER['HTTP_USER_AGENT'] do determine whether we’re in a mobile context.

    Here is a basic page template exemple:

    <?php
    
    /**
     * Template Name: Mobile restricted page
     *
     * @since 1.0.0
     */
    if ( ! wp_is_mobile() ) {
    
        global $wp_query;
    
        $wp_query->set_404();
    
        status_header( 404 );
    
        get_template_part( 404 );
    
        exit();
    
    };
    
    get_header();
    
    //...
    
    get_footer();
    

    But why would you do such an horrible thing !

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search