How to Display Mobile-Only Content on WordPress

This WordPress snippet will use WordPress’s built-in “mobile detection” function “wp_is_mobile” to create a simple shortcode capable of hiding specific parts of your content from mobile or desktop visitors.

Programmazione WordPress
Programmazione WordPress

Did you know you can leverage WordPress’s built-in “mobile detection” function, wp_is_mobile, to create a simple shortcode capable of hiding specific parts of your content from mobile or desktop visitors? The wp_is_mobile function returns true when your site is being viewed from a mobile browser. By using this function in PHP, you can create adaptive/responsive WordPress themes based on the visitor’s device.

<?php
if ( wp_is_mobile() ) {
    // Display only for mobile
    echo 'This content is visible only on mobile devices.';
} else {
    // Display only for desktop
    echo 'This content is visible only on desktops.';
}
?>

Explanation:

  1. The wp_is_mobile function is a built-in WordPress function that returns true if the user is viewing the site from a mobile device, otherwise it returns false.
  2. In our snippet, we use the conditional statement if to check whether wp_is_mobile returns true or false.
  3. If wp_is_mobile returns true, we display a message indicating that the content is visible only on mobile devices.
  4. If wp_is_mobile returns false, we display a message indicating that the content is visible only on desktops.

Make sure to place this code in the correct file within your WordPress theme, such as the functions.php file or the template file where you wish to display the mobile-specific or desktop-specific content.

Pubblicato in

Se vuoi rimanere aggiornato su How to Display Mobile-Only Content on WordPress iscriviti alla nostra newsletter settimanale

Be the first to comment

Leave a Reply

Your email address will not be published.


*