Skip to navigation
Conditional wordpress shortcode
17.02.26
I like to determine the user's screen resolution *before* adding a shortcode to the page content, allowing you to conditionally display different shortcodes based on whether the user is on a mobile or desktop device. Here's how you can achieve this using a combination of JavaScript, cookies, and a WordPress shortcode: **1. JavaScript to Detect Resolution and Set a Cookie:** * Place this JavaScript code in your theme's `footer.php` (or, preferably, enqueue it as a separate `.js` file as described in the previous response). This code will detect the screen width and set a cookie indicating whether the user is likely on a mobile device. ```javascript jQuery(document).ready(function($) { function setCookie(name, value, days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toUTCString(); } document.cookie = name + "=" + (value || "") + expires + "; path=/"; } // Define a threshold for mobile screen width (adjust as needed) var mobileThreshold = 768; // Example: Screens less than 768px wide are considered mobile var screenWidth = screen.width; // Or window.innerWidth, depending on your needs if (screenWidth < mobileThreshold) { setCookie('isMobile', 'true', 1); // Set cookie for 1 day } else { setCookie('isMobile', 'false', 1); } }); ``` * **Explanation:** * `jQuery(document).ready(function($) { ... });`: Ensures the code runs after the DOM is fully loaded. * `setCookie()`: A helper function to set cookies. * `mobileThreshold`: This is a crucial value. It defines the maximum screen width (in pixels) that you consider to be a "mobile" device. Adjust this value based on your design and the breakpoints you use in your CSS. Common values are 768px or 992px. * `screenWidth`: Gets the screen width using `screen.width`. You might want to use `window.innerWidth` instead, depending on whether you want to detect the *screen* width or the *browser window* width. * `if (screenWidth < mobileThreshold) { ... }`: Checks if the screen width is below the threshold. * `setCookie('isMobile', 'true', 1);` or `setCookie('isMobile', 'false', 1);`: Sets a cookie named `isMobile` to either `true` or `false`, indicating whether the user is likely on a mobile device. The cookie expires after 1 day. **2. WordPress Shortcode:** * Add this code to your theme's `functions.php` file (or in a custom plugin): ```php function conditional_shortcode( $atts ) { // Check if the 'isMobile' cookie is set if (isset($_COOKIE['isMobile'])) { $isMobile = $_COOKIE['isMobile']; if ($isMobile === 'true') { // Return shortcode A for mobile users return do_shortcode('[shortcode_a]'); // Replace with your actual shortcode } else { // Return shortcode B for desktop users return do_shortcode('[shortcode_b]'); // Replace with your actual shortcode } } else { // Cookie not set (first visit or cookie blocked). Provide a default. // You might want to return shortcode B (desktop) as a default. return do_shortcode('[shortcode_b]'); // Default to desktop } } add_shortcode( 'conditional_content', 'conditional_shortcode' ); ``` * **Explanation:** * `conditional_shortcode( $atts )`: This is the function that defines your shortcode's behavior. * `if (isset($_COOKIE['isMobile'])) { ... }`: Checks if the `isMobile` cookie exists. * `$isMobile = $_COOKIE['isMobile'];`: Retrieves the value of the `isMobile` cookie. * `if ($isMobile === 'true') { ... }`: Checks if the cookie value is `true` (meaning the user is likely on a mobile device). * `return do_shortcode('[shortcode_a]');`: If the user is on mobile, it executes the shortcode `[shortcode_a]` and returns the result. **Replace `[shortcode_a]` with the actual shortcode you want to use for mobile users.** * `return do_shortcode('[shortcode_b]');`: If the user is on desktop, it executes the shortcode `[shortcode_b]` and returns the result. **Replace `[shortcode_b]` with the actual shortcode you want to use for desktop users.** * `add_shortcode( 'conditional_content', 'conditional_shortcode' );`: Registers the shortcode `[conditional_content]`. **3. Usage in Your WordPress Page:** * In your WordPress page editor, simply add the following shortcode: ``` [conditional_content] ``` * WordPress will then execute the `conditional_shortcode` function, which will check the `isMobile` cookie and display either `[shortcode_a]` or `[shortcode_b]` accordingly. **Important Considerations and Improvements:** * **Cookie Blocking:** Users can block cookies. The `else` block in the shortcode function handles the case where the cookie is not set. It's important to provide a reasonable default (usually the desktop version) in this case. You could also display a message asking users to enable cookies. * **First Visit:** On the very first visit to the page, the cookie won't be set yet. The default behavior in the `else` block will be used. After the page loads and the JavaScript sets the cookie, subsequent page loads will correctly detect the device type. This is a limitation of this approach. You could mitigate this by setting a default cookie value on the server-side based on user agent sniffing, but this is less reliable than screen width detection. * **Caching:** If you are using a caching plugin, make sure it is configured to handle cookies correctly. Some caching plugins might cache the page *before* the JavaScript has a chance to set the cookie, resulting in the wrong shortcode being displayed. You may need to configure your caching plugin to exclude pages with this shortcode or to use dynamic caching based on cookies. * **Mobile Threshold:** Experiment with the `mobileThreshold` value in the JavaScript to find the best value for your design. * **User Agent Sniffing (Less Reliable):** While not recommended as the primary method, you *could* use PHP to detect the user agent string and try to determine if the user is on a mobile device. However, user agent strings are easily spoofed and are not a reliable way to detect device type. Screen width detection is generally more accurate. If you *do* use user agent sniffing, do it *in addition* to the cookie-based approach as a fallback for the first visit. * **Accessibility:** Consider users who might have large screens but use accessibility features that make the content appear smaller. The `window.innerWidth` might be a better choice in this case. * **Testing:** Thoroughly test this solution on various devices and browsers to ensure it works correctly. Use your browser's developer tools to simulate different screen sizes. **Example Shortcodes (Replace these with your actual shortcodes):** * **Shortcode A (Mobile):** `[mobile_ad]` (displays a mobile-optimized ad) * **Shortcode B (Desktop):** `[desktop_ad]` (displays a desktop ad) **Complete Example (functions.php):** ```php // functions.php function conditional_shortcode( $atts ) { if (isset($_COOKIE['isMobile'])) { $isMobile = $_COOKIE['isMobile']; if ($isMobile === 'true') { return do_shortcode('[mobile_ad]'); // Mobile shortcode } else { return do_shortcode('[desktop_ad]'); // Desktop shortcode } } else { return do_shortcode('[desktop_ad]'); // Default to desktop } } add_shortcode( 'conditional_content', 'conditional_shortcode' ); // Example mobile and desktop shortcodes (replace with your actual shortcodes) function mobile_ad_shortcode() { return '
Mobile Ad Content
'; } add_shortcode('mobile_ad', 'mobile_ad_shortcode'); function desktop_ad_shortcode() { return '
Desktop Ad Content
'; } add_shortcode('desktop_ad', 'desktop_ad_shortcode'); ``` This approach provides a way to conditionally display different shortcodes based on the detected screen width, allowing you to tailor the content to mobile and desktop users. Remember to adjust the `mobileThreshold` value and the shortcodes to match your specific needs. Also, carefully consider the limitations and improvements mentioned above. Using CSS media queries is often a better approach for responsive design, but this method can be useful in specific situations where you need to conditionally execute different shortcodes.
Reply
Anonymous
Information Epoch 1772051904
Using text data files.
Home
Notebook
Contact us