Getting Creative with WordPress Queries

Getting Crazy Creative
with WordPress Queries
Drew Jaynes
WordCamp Cape Town 2015
• Platform Engineer at 10up
• Docs Committer for WordPress core
• 4.2 Release Lead
• Developing with WordPress since 2009
• Slides: http://drewf.us/wcct
Hi, I’m Drew.
• Basics
• No-Nos
• Optimizations
• Creative Querying
Topics
Query Basics
The Loop
if ( have_posts() ) :
while ( have_posts() ) :
the_post();
...
endwhile;
endif;
The Loop: Internals
if ( $wp_query->have_posts() ) :
while ( $wp_query->have_posts() ) :
$wp_query->the_post();
...
endwhile;
endif;
WP_Query
// Query for the 7 latest, published posts.
$query = new WP_Query( array(
'posts_per_page' => 7,
'post_status' => 'publish'
) );
WP_Query: SQL
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts
WHERE 1=1
AND wp_posts.post_type = 'post'
AND wp_posts.post_status = 'publish'
ORDER BY wp_posts.post_date DESC
LIMIT 0, 7
• WP_Query wrapper
• Defaults: Filter suppression
• Defaults: No sticky posts
• Defaults: No found rows
• Array of results vs WP_Query instance
get_posts()
get_posts()
// Query for the 7 latest, published posts.
$query = get_posts( array(
'posts_per_page' => 7,
'post_status' => 'publish'
) );
get_posts(): SQL
SELECT wp_posts.ID FROM wp_posts
WHERE 1=1
AND wp_posts.post_type = 'post'
AND ( ( wp_posts.post_status = 'publish' ) )
ORDER BY wp_posts.post_date DESC
LIMIT 0, 7
• Action, not a filter
• Fires before the query actually runs
• Use query methods intead of top-level functio
e.g. $query->is_main_query()
pre_get_posts
pre_get_posts
/**
* Display both posts and pages in the home loop.
*
* @param WP_Query $query Main WP_Query instance.
*/
function pages_in_main_query( $query ) {
if ( ! is_admin() && is_home() ) {
$query->query_vars['post_type'] = array( 'post', 'page' );
}
}
add_action( 'pre_get_posts', 'pages_in_main_query' );
pre_get_posts: Original SQL
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts
WHERE 1=1
AND wp_posts.post_type = 'post'
AND (
wp_posts.post_status = ‘publish'
OR wp_posts.post_status = ‘private'
)
ORDER BY wp_posts.post_date DESC
LIMIT 0, 10
pre_get_posts: SQL
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts
WHERE 1=1
AND wp_posts.post_type IN ( 'post', 'page' )
AND (
wp_posts.post_status = ‘publish'
OR wp_posts.post_status = ‘private'
)
ORDER BY wp_posts.post_date DESC
LIMIT 0, 10
No-Nos
• Completely overrides the main query
• Very few valid use cases
• Custom page template archives
query_posts()
query_posts()
query_posts( array(
'post_type' => ‘page’,
‘post_per_page' => 4
) );
posts_per_page
get_posts( array(
‘posts_per_page’ => -1,
‘posts_per_page’ => 100
) );
Optimization
• update_post_term_cache
• update_post_meta_cache
• no_found_rows
• fields
• posts_per_page
Optimizing WP_Query
Optimizing WP_Query
$query = new WP_Query( array(
'update_post_term_cache' => false,
'update_post_meta_cache' => false,
'posts_per_page' => 100,
'no_found_rows' => true,
'fields' => 'ids'
) );
Creative Querying
WP_Query
• posts_* filters
• pre_get_posts action
WP_Query hooks
WP_Query orderby
$posts = get_posts( array(
'posts_per_page' => 15,
'orderby' => array(
'post_date' => 'DESC',
'post_title' => 'ASC'
),
) );
WP_Query orderby: SQL
SELECT wp_posts.ID FROM wp_posts
WHERE 1=1
AND wp_posts.post_type = 'post'
AND ( ( wp_posts.post_status = 'publish' ) )
ORDER BY wp_posts.post_date DESC, wp_posts.post_title ASC
LIMIT 0, 15
• Available 4.2+
• Order by independent meta clauses
• WP_Meta_Query, WP_User_Query,
WP_Comment_Query
WP_Query orderby: meta clauses
WP_Query orderby: meta clauses
$posts = get_posts( array(
'meta_query' => array(
'relation' => 'AND',
'state_clause' => array(
'key' => 'state',
'value' => 'Colorado'
),
'city_clause' => array(
'key' => 'city',
'compare' => 'EXISTS'
)
),
'orderby' => array(
'state_clause' => 'ASC',
'city_clause' => 'DESC'
)
) );
WP_Query orderby: meta clauses
$posts = get_posts( array(
'meta_query' => array(
'relation' => 'AND',
'state_clause' => array(
'key' => 'state',
'value' => 'Colorado'
),
'city_clause' => array(
'key' => 'city',
'compare' => 'EXISTS'
)
),
'orderby' => array(
'state_clause' => 'ASC',
'city_clause' => 'DESC'
)
) );
WP_Query orderby: SQL
SELECT wp_posts.ID FROM wp_posts
INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )
INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id )
WHERE 1=1
AND (
( wp_postmeta.meta_key = ‘state’
AND CAST( wp_postmeta.meta_value AS CHAR ) = ‘Colorado'
)
AND mt1.meta_key = ‘city'
)
AND wp_posts.post_type = 'post'
AND ( ( wp_posts.post_status = 'publish' ) )
GROUP BY wp_posts.ID
ORDER BY
CAST( mt1.meta_value AS CHAR ) ASC,
CAST( wp_postmeta.meta_value AS CHAR ) DESC
LIMIT 0, 5
WP_User_Query
WP_User_Query
// Query for users registered on a Tuesday.
$query = new WP_User_Query( array(
'date_query' => array(
array(
'column' => 'user_registered',
'dayofweek' => 3 // Tuesday
)
),
) );
Custom WP_Query Orderby
• Order results by a value in a custom table
• Adds an additional LEFT JOIN
WP_Query orderby with custom tables
Joining Custom Tables: JOIN
/**
* Join vote totals table to the 'books' custom post type query.
*
* @param string $join JOIN query clauses.
* @param WP_Query $query Current WP_Query instance.
* @return string The filtered JOIN clauses.
*/
function join_votes_table( $join, $query ) {
global $wpdb;
if ( ! is_admin() ) {
if ( isset( $query->query_vars['post_type'] )
&& 'books' == $query->query_vars[‘post_type']
) {
$votes = $wpdb->prefix . 'up_down_post_vote_totals';
$join .= "LEFT JOIN $votes ON $wpdb->posts.ID = $votes.post_id ";
}
}
return $join;
}
add_filter( 'posts_join', 'join_votes_table', 10, 2 );
Joining Custom Tables: ORDERBY
/**
* Order by vote totals descending, then post date descending.
*
* @param string $orderby ORDER BY query clauses.
* @param WP_Query $query Current WP_Query instance.
* @return string The filtered ORDER BY query clauses.
*/
function orderby_votes_and_date( $orderby, $query ) {
global $wpdb;
if ( ! is_admin() ) {
if ( isset( $query->query_vars['post_type'] )
&& 'books' == $query->query_vars[‘post_type']
) {
$votes = $wpdb->prefix . 'up_down_post_vote_totals';
$orderby = "$votes.vote_count_up DESC, $wpdb->posts.post_date DESC";
}
}
return $orderby;
}
add_filter( 'posts_orderby', 'orderby_votes_and_date', 10, 2 );
Joining Custom Tables: SQL
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts
WHERE 1=1
AND wp_posts.post_type = 'books'
AND ( wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private' )
ORDER BY wp_posts.post_date DESC
LIMIT 0, 10
Original SQL:
Joining Custom Tables: SQL
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts
LEFT JOIN wp_up_down_post_vote_totals
ON wp_posts.ID = wp_up_down_post_vote_totals.post_id
WHERE 1=1
AND wp_posts.post_type = 'books'
AND ( wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private' )
ORDER BY
wp_up_down_post_vote_totals.vote_count_up DESC,
wp_posts.post_date DESC
LIMIT 0, 10
SQL with the JOIN:
• WordPress Code Reference
• WP_Query Reference (Codex)
• Trunk wp-includes/
Resources
Questions?
Drew Jaynes | @DrewAPicture
Slides: http://drewf.us/wcct
1 of 41

Recommended

Getting Creative with WordPress Queries, Again by
Getting Creative with WordPress Queries, AgainGetting Creative with WordPress Queries, Again
Getting Creative with WordPress Queries, AgainDrewAPicture
515 views50 slides
You don’t know query - WordCamp UK Edinburgh 2012 by
You don’t know query - WordCamp UK Edinburgh 2012You don’t know query - WordCamp UK Edinburgh 2012
You don’t know query - WordCamp UK Edinburgh 2012l3rady
978 views53 slides
Wp query by
Wp queryWp query
Wp querySavita Soni
6.6K views33 slides
You Don't Know Query (WordCamp Netherlands 2012) by
You Don't Know Query (WordCamp Netherlands 2012)You Don't Know Query (WordCamp Netherlands 2012)
You Don't Know Query (WordCamp Netherlands 2012)andrewnacin
62.3K views69 slides
[WLDN] Supercharging word press development in 2018 by
[WLDN] Supercharging word press development in 2018[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018Adam Tomat
291 views68 slides
Django Heresies by
Django HeresiesDjango Heresies
Django HeresiesSimon Willison
34K views83 slides

More Related Content

What's hot

WP_Query, pre_get_posts, and eliminating query_posts() by
WP_Query, pre_get_posts, and eliminating query_posts()WP_Query, pre_get_posts, and eliminating query_posts()
WP_Query, pre_get_posts, and eliminating query_posts()Erick Hitter
8.3K views28 slides
Introducing Assetic (NYPHP) by
Introducing Assetic (NYPHP)Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Kris Wallsmith
4K views125 slides
Custom Database Queries in WordPress by
Custom Database Queries in WordPressCustom Database Queries in WordPress
Custom Database Queries in WordPresstopher1kenobe
4.9K views23 slides
Assetic (OSCON) by
Assetic (OSCON)Assetic (OSCON)
Assetic (OSCON)Kris Wallsmith
1.2K views127 slides
Let's write secure Drupal code! - Drupal Camp Poland 2019 by
Let's write secure Drupal code! - Drupal Camp Poland 2019Let's write secure Drupal code! - Drupal Camp Poland 2019
Let's write secure Drupal code! - Drupal Camp Poland 2019Balázs Tatár
206 views113 slides
Let's write secure drupal code! - Drupal Camp Pannonia 2019 by
Let's write secure drupal code! - Drupal Camp Pannonia 2019Let's write secure drupal code! - Drupal Camp Pannonia 2019
Let's write secure drupal code! - Drupal Camp Pannonia 2019Balázs Tatár
575 views112 slides

What's hot(20)

WP_Query, pre_get_posts, and eliminating query_posts() by Erick Hitter
WP_Query, pre_get_posts, and eliminating query_posts()WP_Query, pre_get_posts, and eliminating query_posts()
WP_Query, pre_get_posts, and eliminating query_posts()
Erick Hitter8.3K views
Custom Database Queries in WordPress by topher1kenobe
Custom Database Queries in WordPressCustom Database Queries in WordPress
Custom Database Queries in WordPress
topher1kenobe4.9K views
Let's write secure Drupal code! - Drupal Camp Poland 2019 by Balázs Tatár
Let's write secure Drupal code! - Drupal Camp Poland 2019Let's write secure Drupal code! - Drupal Camp Poland 2019
Let's write secure Drupal code! - Drupal Camp Poland 2019
Balázs Tatár206 views
Let's write secure drupal code! - Drupal Camp Pannonia 2019 by Balázs Tatár
Let's write secure drupal code! - Drupal Camp Pannonia 2019Let's write secure drupal code! - Drupal Camp Pannonia 2019
Let's write secure drupal code! - Drupal Camp Pannonia 2019
Balázs Tatár575 views
Let's write secure Drupal code! - DrupalCamp Oslo, 2018 by Balázs Tatár
Let's write secure Drupal code! - DrupalCamp Oslo, 2018Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Balázs Tatár299 views
Let's write secure Drupal code! DUG Belgium - 08/08/2019 by Balázs Tatár
Let's write secure Drupal code! DUG Belgium - 08/08/2019Let's write secure Drupal code! DUG Belgium - 08/08/2019
Let's write secure Drupal code! DUG Belgium - 08/08/2019
Balázs Tatár288 views
Adventures in Optimization by David Golden
Adventures in OptimizationAdventures in Optimization
Adventures in Optimization
David Golden178 views
Contributing to WordPress Core - Peter Wilson by WordCamp Sydney
Contributing to WordPress Core - Peter WilsonContributing to WordPress Core - Peter Wilson
Contributing to WordPress Core - Peter Wilson
WordCamp Sydney1.3K views
Assetic (Symfony Live Paris) by Kris Wallsmith
Assetic (Symfony Live Paris)Assetic (Symfony Live Paris)
Assetic (Symfony Live Paris)
Kris Wallsmith4.9K views
Image manipulation in WordPress 3.5 by Marko Heijnen
Image manipulation in WordPress 3.5Image manipulation in WordPress 3.5
Image manipulation in WordPress 3.5
Marko Heijnen4.2K views
Childthemes ottawa-word camp-1919 by Paul Bearne
Childthemes ottawa-word camp-1919Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919
Paul Bearne531 views
Let's write secure Drupal code! Drupal MountainCamp 2019 by Balázs Tatár
Let's write secure Drupal code! Drupal MountainCamp 2019Let's write secure Drupal code! Drupal MountainCamp 2019
Let's write secure Drupal code! Drupal MountainCamp 2019
Balázs Tatár244 views
Refactor Dance - Puppet Labs 'Best Practices' by Gary Larizza
Refactor Dance - Puppet Labs 'Best Practices'Refactor Dance - Puppet Labs 'Best Practices'
Refactor Dance - Puppet Labs 'Best Practices'
Gary Larizza1.9K views

Similar to Getting Creative with WordPress Queries

The Query the Whole Query and Nothing but the Query by
The Query the Whole Query and Nothing but the QueryThe Query the Whole Query and Nothing but the Query
The Query the Whole Query and Nothing but the QueryChris Olbekson
1.2K views66 slides
WordPress London 16 May 2012 - You don’t know query by
WordPress London 16 May 2012 - You don’t know queryWordPress London 16 May 2012 - You don’t know query
WordPress London 16 May 2012 - You don’t know queryl3rady
1.1K views53 slides
You Don't Know Query - WordCamp Portland 2011 by
You Don't Know Query - WordCamp Portland 2011You Don't Know Query - WordCamp Portland 2011
You Don't Know Query - WordCamp Portland 2011andrewnacin
11.1K views61 slides
Victoria wordpress by
Victoria wordpressVictoria wordpress
Victoria wordpressFlynn O'Connor
1.2K views21 slides
Supercharging WordPress Development - Wordcamp Brighton 2019 by
Supercharging WordPress Development - Wordcamp Brighton 2019Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019Adam Tomat
612 views64 slides
Can WordPress really do that? A case study of vierderduer.no by
Can WordPress really do that? A case study of vierderduer.noCan WordPress really do that? A case study of vierderduer.no
Can WordPress really do that? A case study of vierderduer.noMorten Rand-Hendriksen
1.7K views63 slides

Similar to Getting Creative with WordPress Queries(20)

The Query the Whole Query and Nothing but the Query by Chris Olbekson
The Query the Whole Query and Nothing but the QueryThe Query the Whole Query and Nothing but the Query
The Query the Whole Query and Nothing but the Query
Chris Olbekson1.2K views
WordPress London 16 May 2012 - You don’t know query by l3rady
WordPress London 16 May 2012 - You don’t know queryWordPress London 16 May 2012 - You don’t know query
WordPress London 16 May 2012 - You don’t know query
l3rady1.1K views
You Don't Know Query - WordCamp Portland 2011 by andrewnacin
You Don't Know Query - WordCamp Portland 2011You Don't Know Query - WordCamp Portland 2011
You Don't Know Query - WordCamp Portland 2011
andrewnacin11.1K views
Supercharging WordPress Development - Wordcamp Brighton 2019 by Adam Tomat
Supercharging WordPress Development - Wordcamp Brighton 2019Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019
Adam Tomat612 views
Can WordPress really do that? A case study of vierderduer.no by Morten Rand-Hendriksen
Can WordPress really do that? A case study of vierderduer.noCan WordPress really do that? A case study of vierderduer.no
Can WordPress really do that? A case study of vierderduer.no
Working with WP_Query in WordPress by topher1kenobe
Working with WP_Query in WordPressWorking with WP_Query in WordPress
Working with WP_Query in WordPress
topher1kenobe1.7K views
Becoming a better WordPress Developer by Joey Kudish
Becoming a better WordPress DeveloperBecoming a better WordPress Developer
Becoming a better WordPress Developer
Joey Kudish1.6K views
Why Hacking WordPress Search Isn't Some Big Scary Thing by Chris Reynolds
Why Hacking WordPress Search Isn't Some Big Scary ThingWhy Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary Thing
Chris Reynolds2K views
WordPress as an application framework by Dustin Filippini
WordPress as an application frameworkWordPress as an application framework
WordPress as an application framework
Dustin Filippini416 views
Wordcamp Fayetteville Pods Presentation (PDF) by mpvanwinkle
Wordcamp Fayetteville Pods Presentation (PDF)Wordcamp Fayetteville Pods Presentation (PDF)
Wordcamp Fayetteville Pods Presentation (PDF)
mpvanwinkle545 views
WordPress Café: Using WordPress as a Framework by Exove
WordPress Café: Using WordPress as a FrameworkWordPress Café: Using WordPress as a Framework
WordPress Café: Using WordPress as a Framework
Exove1.1K views
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT) by Mike Schinkel
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Mike Schinkel10.5K views
DrupalCamp Foz - Novas APIs Drupal 7 by chuvainc
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
chuvainc1.5K views
The Way to Theme Enlightenment by Amanda Giles
The Way to Theme EnlightenmentThe Way to Theme Enlightenment
The Way to Theme Enlightenment
Amanda Giles1.6K views

More from DrewAPicture

WordPress Development in a Modern PHP World by
WordPress Development in a Modern PHP WorldWordPress Development in a Modern PHP World
WordPress Development in a Modern PHP WorldDrewAPicture
1.3K views72 slides
WordPress Development in a Modern PHP World by
WordPress Development in a Modern PHP WorldWordPress Development in a Modern PHP World
WordPress Development in a Modern PHP WorldDrewAPicture
737 views68 slides
How to Win Friends and Influence WordPress Core by
How to Win Friends and Influence WordPress CoreHow to Win Friends and Influence WordPress Core
How to Win Friends and Influence WordPress CoreDrewAPicture
313 views30 slides
Trying Out Tomorrow’s WordPress Today by
Trying Out Tomorrow’s WordPress TodayTrying Out Tomorrow’s WordPress Today
Trying Out Tomorrow’s WordPress TodayDrewAPicture
13.4K views32 slides
It Takes a Village to Make WordPress by
It Takes a Village to Make WordPressIt Takes a Village to Make WordPress
It Takes a Village to Make WordPressDrewAPicture
4.1K views33 slides
Setting Up WordPress: A NUX Case Study by
Setting Up WordPress: A NUX Case StudySetting Up WordPress: A NUX Case Study
Setting Up WordPress: A NUX Case StudyDrewAPicture
4.9K views34 slides

More from DrewAPicture(11)

WordPress Development in a Modern PHP World by DrewAPicture
WordPress Development in a Modern PHP WorldWordPress Development in a Modern PHP World
WordPress Development in a Modern PHP World
DrewAPicture1.3K views
WordPress Development in a Modern PHP World by DrewAPicture
WordPress Development in a Modern PHP WorldWordPress Development in a Modern PHP World
WordPress Development in a Modern PHP World
DrewAPicture737 views
How to Win Friends and Influence WordPress Core by DrewAPicture
How to Win Friends and Influence WordPress CoreHow to Win Friends and Influence WordPress Core
How to Win Friends and Influence WordPress Core
DrewAPicture313 views
Trying Out Tomorrow’s WordPress Today by DrewAPicture
Trying Out Tomorrow’s WordPress TodayTrying Out Tomorrow’s WordPress Today
Trying Out Tomorrow’s WordPress Today
DrewAPicture13.4K views
It Takes a Village to Make WordPress by DrewAPicture
It Takes a Village to Make WordPressIt Takes a Village to Make WordPress
It Takes a Village to Make WordPress
DrewAPicture4.1K views
Setting Up WordPress: A NUX Case Study by DrewAPicture
Setting Up WordPress: A NUX Case StudySetting Up WordPress: A NUX Case Study
Setting Up WordPress: A NUX Case Study
DrewAPicture4.9K views
Core Docs: Sentencing WordPress to 11-years-to-life by DrewAPicture
Core Docs: Sentencing WordPress to 11-years-to-lifeCore Docs: Sentencing WordPress to 11-years-to-life
Core Docs: Sentencing WordPress to 11-years-to-life
DrewAPicture5.2K views
Putting the (docs) Cart Before the (standards) Horse by DrewAPicture
Putting the (docs) Cart Before the (standards) HorsePutting the (docs) Cart Before the (standards) Horse
Putting the (docs) Cart Before the (standards) Horse
DrewAPicture1.2K views
There's a Filter For That by DrewAPicture
There's a Filter For ThatThere's a Filter For That
There's a Filter For That
DrewAPicture12.1K views
Customizer-ing Theme Options: A Visual Playground by DrewAPicture
Customizer-ing Theme Options: A Visual PlaygroundCustomizer-ing Theme Options: A Visual Playground
Customizer-ing Theme Options: A Visual Playground
DrewAPicture4.7K views
Anatomy of the WordPress Loop by DrewAPicture
Anatomy of the WordPress LoopAnatomy of the WordPress Loop
Anatomy of the WordPress Loop
DrewAPicture1.6K views

Recently uploaded

Meet the Bible by
Meet the BibleMeet the Bible
Meet the BibleSteve Thomason
69 views80 slides
How to empty an One2many field in Odoo by
How to empty an One2many field in OdooHow to empty an One2many field in Odoo
How to empty an One2many field in OdooCeline George
97 views8 slides
REPRESENTATION - GAUNTLET.pptx by
REPRESENTATION - GAUNTLET.pptxREPRESENTATION - GAUNTLET.pptx
REPRESENTATION - GAUNTLET.pptxiammrhaywood
151 views26 slides
Retail Store Scavenger Hunt.pptx by
Retail Store Scavenger Hunt.pptxRetail Store Scavenger Hunt.pptx
Retail Store Scavenger Hunt.pptxjmurphy154
47 views10 slides
Relationship of psychology with other subjects. by
Relationship of psychology with other subjects.Relationship of psychology with other subjects.
Relationship of psychology with other subjects.palswagata2003
77 views16 slides
Pharmaceutical Inorganic Chemistry Unit IVMiscellaneous compounds Expectorant... by
Pharmaceutical Inorganic Chemistry Unit IVMiscellaneous compounds Expectorant...Pharmaceutical Inorganic Chemistry Unit IVMiscellaneous compounds Expectorant...
Pharmaceutical Inorganic Chemistry Unit IVMiscellaneous compounds Expectorant...Ms. Pooja Bhandare
166 views45 slides

Recently uploaded(20)

How to empty an One2many field in Odoo by Celine George
How to empty an One2many field in OdooHow to empty an One2many field in Odoo
How to empty an One2many field in Odoo
Celine George97 views
REPRESENTATION - GAUNTLET.pptx by iammrhaywood
REPRESENTATION - GAUNTLET.pptxREPRESENTATION - GAUNTLET.pptx
REPRESENTATION - GAUNTLET.pptx
iammrhaywood151 views
Retail Store Scavenger Hunt.pptx by jmurphy154
Retail Store Scavenger Hunt.pptxRetail Store Scavenger Hunt.pptx
Retail Store Scavenger Hunt.pptx
jmurphy15447 views
Relationship of psychology with other subjects. by palswagata2003
Relationship of psychology with other subjects.Relationship of psychology with other subjects.
Relationship of psychology with other subjects.
palswagata200377 views
Pharmaceutical Inorganic Chemistry Unit IVMiscellaneous compounds Expectorant... by Ms. Pooja Bhandare
Pharmaceutical Inorganic Chemistry Unit IVMiscellaneous compounds Expectorant...Pharmaceutical Inorganic Chemistry Unit IVMiscellaneous compounds Expectorant...
Pharmaceutical Inorganic Chemistry Unit IVMiscellaneous compounds Expectorant...
Ms. Pooja Bhandare166 views
GCSE Geography by WestHatch
GCSE GeographyGCSE Geography
GCSE Geography
WestHatch47 views
The basics - information, data, technology and systems.pdf by JonathanCovena1
The basics - information, data, technology and systems.pdfThe basics - information, data, technology and systems.pdf
The basics - information, data, technology and systems.pdf
JonathanCovena1156 views
BÀI TẬP BỔ TRỢ TIẾNG ANH FAMILY AND FRIENDS NATIONAL EDITION - LỚP 4 (CÓ FIL... by Nguyen Thanh Tu Collection
BÀI TẬP BỔ TRỢ TIẾNG ANH FAMILY AND FRIENDS NATIONAL EDITION - LỚP 4 (CÓ FIL...BÀI TẬP BỔ TRỢ TIẾNG ANH FAMILY AND FRIENDS NATIONAL EDITION - LỚP 4 (CÓ FIL...
BÀI TẬP BỔ TRỢ TIẾNG ANH FAMILY AND FRIENDS NATIONAL EDITION - LỚP 4 (CÓ FIL...
The Accursed House by Émile Gaboriau by DivyaSheta
The Accursed House  by Émile GaboriauThe Accursed House  by Émile Gaboriau
The Accursed House by Émile Gaboriau
DivyaSheta234 views
Classification of crude drugs.pptx by GayatriPatra14
Classification of crude drugs.pptxClassification of crude drugs.pptx
Classification of crude drugs.pptx
GayatriPatra14104 views
A-Level Art by WestHatch
A-Level ArtA-Level Art
A-Level Art
WestHatch48 views
AUDIENCE - BANDURA.pptx by iammrhaywood
AUDIENCE - BANDURA.pptxAUDIENCE - BANDURA.pptx
AUDIENCE - BANDURA.pptx
iammrhaywood131 views
JQUERY.pdf by ArthyR3
JQUERY.pdfJQUERY.pdf
JQUERY.pdf
ArthyR396 views
When Sex Gets Complicated: Porn, Affairs, & Cybersex by Marlene Maheu
When Sex Gets Complicated: Porn, Affairs, & CybersexWhen Sex Gets Complicated: Porn, Affairs, & Cybersex
When Sex Gets Complicated: Porn, Affairs, & Cybersex
Marlene Maheu99 views

Getting Creative with WordPress Queries

  • 1. Getting Crazy Creative with WordPress Queries Drew Jaynes WordCamp Cape Town 2015
  • 2. • Platform Engineer at 10up • Docs Committer for WordPress core • 4.2 Release Lead • Developing with WordPress since 2009 • Slides: http://drewf.us/wcct Hi, I’m Drew.
  • 3. • Basics • No-Nos • Optimizations • Creative Querying Topics
  • 5. The Loop if ( have_posts() ) : while ( have_posts() ) : the_post(); ... endwhile; endif;
  • 6. The Loop: Internals if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post(); ... endwhile; endif;
  • 7. WP_Query // Query for the 7 latest, published posts. $query = new WP_Query( array( 'posts_per_page' => 7, 'post_status' => 'publish' ) );
  • 8. WP_Query: SQL SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND wp_posts.post_status = 'publish' ORDER BY wp_posts.post_date DESC LIMIT 0, 7
  • 9. • WP_Query wrapper • Defaults: Filter suppression • Defaults: No sticky posts • Defaults: No found rows • Array of results vs WP_Query instance get_posts()
  • 10. get_posts() // Query for the 7 latest, published posts. $query = get_posts( array( 'posts_per_page' => 7, 'post_status' => 'publish' ) );
  • 11. get_posts(): SQL SELECT wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND ( ( wp_posts.post_status = 'publish' ) ) ORDER BY wp_posts.post_date DESC LIMIT 0, 7
  • 12. • Action, not a filter • Fires before the query actually runs • Use query methods intead of top-level functio e.g. $query->is_main_query() pre_get_posts
  • 13. pre_get_posts /** * Display both posts and pages in the home loop. * * @param WP_Query $query Main WP_Query instance. */ function pages_in_main_query( $query ) { if ( ! is_admin() && is_home() ) { $query->query_vars['post_type'] = array( 'post', 'page' ); } } add_action( 'pre_get_posts', 'pages_in_main_query' );
  • 14. pre_get_posts: Original SQL SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND ( wp_posts.post_status = ‘publish' OR wp_posts.post_status = ‘private' ) ORDER BY wp_posts.post_date DESC LIMIT 0, 10
  • 15. pre_get_posts: SQL SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type IN ( 'post', 'page' ) AND ( wp_posts.post_status = ‘publish' OR wp_posts.post_status = ‘private' ) ORDER BY wp_posts.post_date DESC LIMIT 0, 10
  • 17. • Completely overrides the main query • Very few valid use cases • Custom page template archives query_posts()
  • 18. query_posts() query_posts( array( 'post_type' => ‘page’, ‘post_per_page' => 4 ) );
  • 19. posts_per_page get_posts( array( ‘posts_per_page’ => -1, ‘posts_per_page’ => 100 ) );
  • 21. • update_post_term_cache • update_post_meta_cache • no_found_rows • fields • posts_per_page Optimizing WP_Query
  • 22. Optimizing WP_Query $query = new WP_Query( array( 'update_post_term_cache' => false, 'update_post_meta_cache' => false, 'posts_per_page' => 100, 'no_found_rows' => true, 'fields' => 'ids' ) );
  • 25. • posts_* filters • pre_get_posts action WP_Query hooks
  • 26. WP_Query orderby $posts = get_posts( array( 'posts_per_page' => 15, 'orderby' => array( 'post_date' => 'DESC', 'post_title' => 'ASC' ), ) );
  • 27. WP_Query orderby: SQL SELECT wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND ( ( wp_posts.post_status = 'publish' ) ) ORDER BY wp_posts.post_date DESC, wp_posts.post_title ASC LIMIT 0, 15
  • 28. • Available 4.2+ • Order by independent meta clauses • WP_Meta_Query, WP_User_Query, WP_Comment_Query WP_Query orderby: meta clauses
  • 29. WP_Query orderby: meta clauses $posts = get_posts( array( 'meta_query' => array( 'relation' => 'AND', 'state_clause' => array( 'key' => 'state', 'value' => 'Colorado' ), 'city_clause' => array( 'key' => 'city', 'compare' => 'EXISTS' ) ), 'orderby' => array( 'state_clause' => 'ASC', 'city_clause' => 'DESC' ) ) );
  • 30. WP_Query orderby: meta clauses $posts = get_posts( array( 'meta_query' => array( 'relation' => 'AND', 'state_clause' => array( 'key' => 'state', 'value' => 'Colorado' ), 'city_clause' => array( 'key' => 'city', 'compare' => 'EXISTS' ) ), 'orderby' => array( 'state_clause' => 'ASC', 'city_clause' => 'DESC' ) ) );
  • 31. WP_Query orderby: SQL SELECT wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) WHERE 1=1 AND ( ( wp_postmeta.meta_key = ‘state’ AND CAST( wp_postmeta.meta_value AS CHAR ) = ‘Colorado' ) AND mt1.meta_key = ‘city' ) AND wp_posts.post_type = 'post' AND ( ( wp_posts.post_status = 'publish' ) ) GROUP BY wp_posts.ID ORDER BY CAST( mt1.meta_value AS CHAR ) ASC, CAST( wp_postmeta.meta_value AS CHAR ) DESC LIMIT 0, 5
  • 33. WP_User_Query // Query for users registered on a Tuesday. $query = new WP_User_Query( array( 'date_query' => array( array( 'column' => 'user_registered', 'dayofweek' => 3 // Tuesday ) ), ) );
  • 35. • Order results by a value in a custom table • Adds an additional LEFT JOIN WP_Query orderby with custom tables
  • 36. Joining Custom Tables: JOIN /** * Join vote totals table to the 'books' custom post type query. * * @param string $join JOIN query clauses. * @param WP_Query $query Current WP_Query instance. * @return string The filtered JOIN clauses. */ function join_votes_table( $join, $query ) { global $wpdb; if ( ! is_admin() ) { if ( isset( $query->query_vars['post_type'] ) && 'books' == $query->query_vars[‘post_type'] ) { $votes = $wpdb->prefix . 'up_down_post_vote_totals'; $join .= "LEFT JOIN $votes ON $wpdb->posts.ID = $votes.post_id "; } } return $join; } add_filter( 'posts_join', 'join_votes_table', 10, 2 );
  • 37. Joining Custom Tables: ORDERBY /** * Order by vote totals descending, then post date descending. * * @param string $orderby ORDER BY query clauses. * @param WP_Query $query Current WP_Query instance. * @return string The filtered ORDER BY query clauses. */ function orderby_votes_and_date( $orderby, $query ) { global $wpdb; if ( ! is_admin() ) { if ( isset( $query->query_vars['post_type'] ) && 'books' == $query->query_vars[‘post_type'] ) { $votes = $wpdb->prefix . 'up_down_post_vote_totals'; $orderby = "$votes.vote_count_up DESC, $wpdb->posts.post_date DESC"; } } return $orderby; } add_filter( 'posts_orderby', 'orderby_votes_and_date', 10, 2 );
  • 38. Joining Custom Tables: SQL SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'books' AND ( wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private' ) ORDER BY wp_posts.post_date DESC LIMIT 0, 10 Original SQL:
  • 39. Joining Custom Tables: SQL SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN wp_up_down_post_vote_totals ON wp_posts.ID = wp_up_down_post_vote_totals.post_id WHERE 1=1 AND wp_posts.post_type = 'books' AND ( wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private' ) ORDER BY wp_up_down_post_vote_totals.vote_count_up DESC, wp_posts.post_date DESC LIMIT 0, 10 SQL with the JOIN:
  • 40. • WordPress Code Reference • WP_Query Reference (Codex) • Trunk wp-includes/ Resources
  • 41. Questions? Drew Jaynes | @DrewAPicture Slides: http://drewf.us/wcct