I’m trying to limit my posts on WordPress if the screen width is less than 480px (mobile device, responsive).
However I ran into problem as I found out you cannot use PHP to detect screen width, which I require because I’m using PHP to adjust the post numbers. I was hoping for something like:
<?php /* Start the Loop */ ?>
<?php if media-screen < 480px {
query_posts('posts_per_page=5'); } ?>
<?php while (have_posts()) : the_post(); ?>
Any suggestions? Can you somehow pass a css/javascript boolean into the php script?
EDIT: I’d rather not redirect visitors to a mobile site as that’s way out of my league.
I’m not a fan of this solution, but you could simply add an element with the number of posts you want to show on mobile that is hidden by default and only shown when the media-query condition is met.
Imagine the following html containing your mobile posts
The via a simple media query you toggle the visibiliy of your wrapper elements:
A more sophisticated (and imho better) approach would be to either annotate the elements you would want to hide (by adding a class) via javascript/php or even CSS3
:nth-child()
selectors. Imagine the following javascript loopwith this CSS
Together those would hide all but the first five posts on a device where the viewport matches. But then you would have to take pagination properly into account.
I think you may benefit from using 51Degrees PHP solution. It is essentially a device detector that uses User Agent string in order to match device against devices from database file. It is available as a WordPress plugin and can be configured through the admin panel.
You can use this plugin to set up a rule that supplies a different theme for devices with the desired screen size. You can set up as many rules as you want with many different combinations. With the basic device info you have over 50 device properties to choose from:
This way you can supply a different theme that will show less posts for mobile devices without having to do any coding (you can supply an entirely different theme or copy your current theme but change number of posts to 5). In case you don’t want to add plugins to your WordPress you can add same functionality by downloading the detector from sourceforge and adding the following lines of code to your theme:
Hope this helps.
Use this function for mobile condition