Wordpress wp_is_mobile() function not working

2019-08-01 19:19发布

I have a plugin on my Wordpress that I want to block when a user is on mobile. In my functions.php I added the line:

if (wp_is_mobile())
{
    wp_dequeue_script('flare');
    wp_deregister_script('flare');
}

Unfortunately, this made the script not load for both mobile and desktop users. So I need to figure out a way to make this script unload if they are on mobile.

I used a similar function inside my post-template, for adding regular share buttons at the bottom of the post if they were on mobile - but this also didn't work. It added the share buttons for both mobile and desktop users.

Any help would be greatly appreciated!

2条回答
来,给爷笑一个
2楼-- · 2019-08-01 19:51

I think Script dequeuing calls should be added to the wp_print_scripts action hook.

Scripts are normally enqueued on the wp_enqueue_script hook, which happens early in the wp_head process. The wp_print_scripts hook happens right before scripts are printed. So I think you should be doing as follows :

function deque_my_scripts () {
    wp_dequeue_script('flare');
    wp_deregister_script('flare');
}

if (wp_is_mobile())
{
   add_action('wp_print_scripts','deque_my_scripts');
}

You can also add the action hook to wp_enqueue_scripts

So another method will be

if (wp_is_mobile())
{
   add_action('wp_enqueue_scripts','deque_my_scripts', 20);

}

Hope this helps you :-)

查看更多
Explosion°爆炸
3楼-- · 2019-08-01 20:01

Try this...

if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false
                    || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false
                    || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false
                    || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false
                    || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false
                    || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false
                    || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false ) {
                    //Mobile browser do stuff here       
        } else {
                    //Do stuff here
            }
查看更多
登录 后发表回答