All posts tagged “Query”

A Look Into: Creating Custom WordPress Query

Today, we are going to take a look at WordPress Query. Even though WordPress has documented its Query function, it is very intimidating and probably impractical to dive into each of the sections. This is the shortcut you need.

In this post we will be discussing a few practical tips on applying WordPress Query that you might need to frequently use on your theme.

Basic WP_Query

In short, WP_Query is a class to request WordPress posts and pages. We can create a new WP_Query class in a WordPress theme to query posts (or pages) in customized specification.

First, let’s take a look at the index.php within your theme directory; you should find the following piece of codes.

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php endwhile; else: ?> <p><?php _e('Sorry, no posts matched your criteria.'); ?></p> <?php endif; ?> 

It’s called Loop. It by default displays all the posts that have been published.

Let’s see how we can customize it with WP_Query. In this example, we are going to exclude posts from a specific category.

First, we set a new WP_Query in a variable.

 $  my_query = new WP_Query(); 

Within it, we can assign the category ID that we want to exclude. For example:

 $  my_query = new WP_Query('cat=-1,-5'); //exclude category 1 and 5 

Then, we refer to the variable within the Loop, as follow.

 <?php if ( $  my_custom_query->have_posts() ) : while ( $  my_custom_query->have_posts() ) : $  my_custom_query->the_post(); ?> <div class="title"> <a href="<?php the_permalink() ;?>"><?php the_title() ;?></a> </div> <?php endwhile; else: ?> <p> <?php _e('Sorry, no posts matched your criteria.'); ?> </p> <?php endif; ?> 

Note that when you have multiple custom queries, particularly within a single page, you have to enclose it with wp_reset_postdata().

Assigning Query with WP-PageNavi

WP-PageNavi is probably the most popular plugin to add numbered pagination in WordPress. Most people however encounter an error when they use it along with custom WP_Query. The pagination simply won’t work.

Since version 2.74, WP-PageNavi has provided an option where you can assign custom query. Taking the above custom query as our example, we can do the following:

 wp_pagenavi( array( 'query' => $  my_query ) ); 

… and that should solve the error.

Cache Query

It should be noted that when you have multiple queries, particularly on a single page, you will end up with multiple server loads which could affect your site load performance.

One of the ways to optimize it is by using Transient API. In this case, we use it to cache the queried object from WP_Query, and store it in a certain period of time.

That way, we can speed up query load times by retrieving and processing the cached data rather than querying it everytime the page is loaded.

Here is a code example, where the cache is stored for 24 hours.

 if ( ! ( $  my_query = get_transient( 'my_query_cache' ) ) ) { $  my_query = new WP_Query('cat=-1,-5'); set_transient( 'my_query_cache', $  my_query, DAY_IN_SECONDS ); } 

Wrap Up

With WP_Query, we can create a simple or more complex queries. If writing a custom WP_Query seems complicated to you, there is a tool called WP_Query Generator that will make it easier.

I hope you will find this tip useful, and if you want to dig into this topic further, below are some references:

A look into: WordPress Date Query

We can display posts published on specific dates with the date parameters in WP_Query. The functionality, however, is basic. We can query posts by day, year, and month, but we were not able to query posts within a certain timeframe. Having been a victim once, I used a hack.

However (thanks to Alex Millis who contributed the code), in version 3.7, released recently, WordPress included Advanced Date Query which allows us to display more complex date-based post queries natively with WP_Query. With this, we can display posts that are published before or after certain hours. Let’s have a look at it.

Advanced Date Query

Version 3.7 introduced a new parameter called date_query. How do you use it?

Say, you are working on a news site, and want to highlight the news (or posts) from the previous week. By using date_query, we can write like so:

 $  last_week_news = new WP_Query( array( 'date_query' => array( array( 'after' => '1 week ago', ), ), 'posts_per_page' => 5, )); $  query = new WP_Query( $  last_week_news ); 

We can also display posts in a very specific timeframe. Below is an example of how we display posts between 15 December 2012 and 15 January 2013. This helps feature end of the year to the turn of the new year stories.

 $  new_year_stories = new WP_Query( array( 'date_query' => array( array( 'after' => 'December 15th, 2012', 'before' => 'January 15th, 2013', ), ), 'posts_per_page' => 5, )); $  query = new WP_Query( $  new_year_stories ); 

And, as mentioned, we can also display posts that were published in certain hours.

If your news website need to feature morning newsbits, you can write the code with date_query this way.

 $  morning_news = array( 'date_query' => array( array( 'hour' => 6, 'compare' => '>=', ), array( 'hour' => 9, 'compare' => '<=', ), ), 'posts_per_page' => 10, ); $  query = new WP_Query( $  morning_news ); 

It’s simpler, straightforward, and the code is more readable.

Final Thought

With the addition of advanced date query, WP_Query has become even more extensive. If keeping track of dates is important on your site e.g. if you are an event organizer or host multiple conferences or conventions, this new feature will definitely be very helpful.

For further reference, you can head over to the WordPress Codex page for Date Parameters.

Retina Display Ready with Media Query

Apple set a new standard in device screen resolution with Retina display. With million of pixels, Retina display delivers more vibrant, more detailed and sharper images on the screen. However, this affects the way on designers and developers deliver the images on these devices, as images that are not optimized for high-resolution screen will look less than stellar.

So, in today’s post, we will look into how to deliver specific image that are optimized for high-resolution screens.

Using Vector Graphic

First of all, if the images do not require realism or a complex color scheme, using Vector graphic is probably your best option. Unlike Raster image, Vector graphic is not dependent on pixels, so it will be displayed fine and sharp on any screen resolution.

There are a few ways to add Vector Graphic on the Web, we can either use SVG, Fonts, or also Canvas previously discussed in:

Using Media Query

There is another way. We can conditionally deliver optimized graphic for specific screen resolutions using Media Query. The syntax is similar to Media Query for establishing responsive layout. However, rather than specifying the viewport width breakpoint, it specifies the device pixel ratio (dpr) and screen resolution threshold.

 @media only screen and (min-device-pixel-ratio: 2), only screen and (min-resolution: 192dpi) { /* Style Rules */ }

The Media Query we showed in the above example will assign the styles for screen resolution with a minimum device pixel ratio of 2 or with minimum resolution of 192dpi.

We can retrieve the dpi number by dividing the screen resolution with its diagonal inches.

For example, a 13.3 inches screen with 1280×800 resolution will give us 96(dpi). So, the number of 196 that we’ve shown in the above code snippet is simply around double that number (96dpi).

In term of getting the device pixel ratio, it is rather scientific. But, in case you are keen on doing the Math, Boris Smush over at HTML5 Rocks will show you how in this article.

Alternatively, we can also query the pixel ratio number through window.devicePixelRatio. In the following example, we return the value from window.devicePixelRatio with an alert window.

 var dpr = window.devicePixelRatio; alert('Device Pixel Ratio: ' + dpr);

This will give use the following result in Retina display screen, like the new MacBook Pro, and iPhone 4.

In non-Retina Display, the number will return 1.

In addition, below is a list of Device Pixel Ratios for popular devices for your reference.

Device Device Pixel Ratio
iPhone 4, iPhone 4S, iPhone 5, iPod Touch 2
iPad with Retina Display 2
Galaxy Nexus, Galaxy Note, Galaxy SIII 2
Kindle Fire HD 1.5
Galaxy S Plus, Galaxy SII 1.5

From the table, you can see that there are some HD screens with 1.5 dpr. So, it is better to set the minimum threshold in Media Query for 1.5 to cover more screen resolutions.

 @media only screen and (min-device-pixel-ratio: 1.5), only screen and (min-resolution: 192dpi) { /* style rules */ }

Also, for wider compatibility across the browsers, we can also add min-device-pixel-ratio with their respective vendor prefixes, like so.

 @media only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and ( min--moz-device-pixel-ratio: 1.5), only screen and ( -o-min-device-pixel-ratio: 3/2), only screen and ( min-device-pixel-ratio: 1.5), only screen and (min-resolution: 192dpi) { /* Style Rules */ } 


We have created a page for demonstration. In this page, we assigned two image formats: a .png image for normal screen resolution and an SVG for the HD screen, which will be assigned through Media Query, like so.

 a { background-image: url('img/hongkiatcom.png'); background-size: 100%; background-repeat: no-repeat; } @media only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and ( min--moz-device-pixel-ratio: 1.5), only screen and ( -o-min-device-pixel-ratio: 3/2), only screen and ( min-device-pixel-ratio: 1.5), only screen and (min-resolution: 192dpi) { a { width: 100%; background-image: url('img/hongkiatcom.svg'); background-size: 100%; background-repeat: no-repeat; } } 

Now, you can test the demo in action through normal and Retina display. It will also show the image name, which is being displayed on the page.

Further Resources