Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.
WordCamp Portland 2011September 17, 2011
Andrew NacinCore Developer of WordPressTech Ninja at Audrey Capitalnacin@wordpress.org@nacin on Twitter
You Dont Know Query
What do you know?
Conditional Tagsis_author( ), is_home( ), etc.
Who has ever heard ofquery_posts( )?
Ways to queryquery_posts( )new WP_Query( )get_posts( )
The loopif ( have_posts( ) )   while ( have_posts( ) ) :      the_post( );  endwhile( );
What dont you know?
Every query object has itsown methodsis_author( ) is the same as calling$wp_query->is_author( )
function is_author( ) {  global $wp_query;    return $wp_query->is_author( );}
If you do:$my_query = new WP_Query( $query );You can do:while ( $my_query->have_posts( ) ) : $my_query->the_post( );endwhi...
But why do we call things likewp_reset_postdata( ) andwp_reset_query( )?What about using query_posts( )?How can you alter ...
What is the main query,and why should I care?
Lets dig in.
wp-blog-header.php// Load the WordPress bootstraprequire dirname( __FILE__ ) . /wp-load.php;// Do magicwp();// Decide whic...
Lets look in the bootstrap:$wp_the_query = new WP_Query();$wp_query =& $wp_the_query;
Quick lesson on PHP references$a = 4;$b =& $a;$b = 2;var_dump( $a ); // int(2)$a = 6;var_dump( $b ); // int(6)
So:So the real main query is in$wp_the_query.And a live copy of it is stored in$wp_query.
wp-blog-header.php// Load the WordPress bootstraprequire dirname( __FILE__ ) . /wp-load.php;// Do magicwp();// Decide whic...
wp-blog-header.php// Load the WordPress bootstraprequire dirname( __FILE__ ) . /wp-load.php;// Do magicwp( );// Decide whi...
What is that wp( ) call?function wp( $query_vars =  ) {  global $wp;    $wp->main( $query_vars );}
Holy $!@?, what justhappened?
In the bootstrap:$wp = new WP( );So theres a wp( ) function,and a WP class.
class WP {    . . .    function main( ) {        $this->init( );        $this->parse_request( );        $this->send_header...
class WP {    . . .    function main( ) {        $this->init( );        $this->parse_request( );        $this->send_header...
WP::parse_request( )— Parses the URL using WP_Rewrite— Sets up query variables for WP_QueryWP::query_posts( ) {  global $w...
Boom.SELECT SQL_CALC_FOUND_ROWS  wp_posts.*FROM wp_postsWHERE 1=1  AND wp_posts.post_type = post  AND wp_posts.post_status...
wp-blog-header.php// Load WordPress.require dirname(__FILE__) . /wp-load.php;// Parse what to query, and query it.wp();// ...
Before we get to the theme,we have your posts.Got it?
Then why do we do this?query_posts( author=5 );get_header( );while( have_posts( ) ) :  the_post( );endwhile;get_footer( );
Thats running 2* queries!One, the query WordPressthought we wanted.Two, this new one youreactually going to use.
* Actually, WP_Querydoesnt run just one query.It usually runs four.
1. Get me my posts:     SELECT     SQL_CALC_FOUND_ROWS …     FROM wp_posts LIMIT 0, 102. How many posts exist?     SELECT ...
PROTIP‘Measure twice, cut once’is bad for performance.
(A note, you can turn these off selectively…)$my_query = new WP_Query( array(     no_found_rows => true,     update_post_me...
So. Instead of this:query_posts( author=5 );get_header( );while ( have_posts( ) ) :  the_post( );endwhile;get_footer( );
We can use this:// In WP::parse_request()$this->query_vars =   apply_filters( request, $this->query_vars );
We can modify queryvariables in mid air:function nacin_filter_out_author( $qvs ) {  if ( ! isset( $qvs[author] ) )         ...
Powerful, but lacks context.
Powerful, but lacks context.Problem 1: Conditional tags dont work yet.
Powerful, but lacks context.Problem 1: Conditional tags dont work yet.Problem 2: Only works on the main query.
Powerful, but lacks context.Problem 1: Conditional tags dont work yet.Problem 2: Only works on the main query.Problem 3: W...
Introducing pre_get_postsclass WP_Query {   . . .   function &get_posts() {       $this->parse_query();       // Huzzah! C...
A truly awesome hook.function nacin_alter_home( $query ) {  if ( $query->is_home( ) )         $query->set( author, -5 );}a...
Still with us?Good, ‘cause here’s wherethings get hairy.
request fires for the main query only.pre_get_posts fires for every post query:— get_posts()— new WP_Query()— That random re...
What if I just want it on themain query?
$wp_the_query makes atriumphant return.
Main query only!function nacin_alter_home ( $query ) {  if ( $wp_the_query === $query             && $query->is_home() )  ...
Hmm. How does this work?$wp_the_query should never be modified. Itholds the main query, forever.$wp_query keeps a live refe...
query_posts( author=-5 );while ( have_posts( ) ) :  the_post( );endwhile;wp_reset_query( );
query_posts( author=-5 );while ( have_posts( ) ) :  the_post( );endwhile;wp_reset_query( );
class WP_Query {   . . .   function &query_posts( $query ) {         // Break the reference to $wp_the_query         unset...
query_posts( author=-5 );while ( have_posts( ) ) :  the_post( );endwhile;wp_reset_query( );
class WP_Query {   . . .       function wp_reset_query( ) {           // Restore the reference to$wp_the_query           u...
Calling the_post( )?  wp_reset_query( ) will reset $wp_query  and and the globals.Calling $my_query->the_post( )?  wp_rese...
New thing for core in 3.3!Rather than:     $wp_the_query === $other_query_object	  Youll be able to call:     $other_query...
Some LessonsEvery WP_Query object has methods thatmimic the global conditional tags.The global conditional tags apply to$w...
And Finallyrequest is a nice hook. pre_get_posts is morepowerful and flexible. Just use it properly.Always check if youre m...
Thanks! Questions?@nacin
Nächste SlideShare
Wird geladen in …5
×

You Don't Know Query - WordCamp Portland 2011

18.580 Aufrufe

Veröffentlicht am

The slides for my talk, You Don't Know Query, at WordCamp Portland on September 17, 2011.

Veröffentlicht in: Technologie
  • DOWNLOAD THAT BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { http://bit.ly/2m77EgH } ......................................................................................................................... Download Full EPUB Ebook here { http://bit.ly/2m77EgH } ......................................................................................................................... Download Full doc Ebook here { http://bit.ly/2m77EgH } ......................................................................................................................... Download PDF EBOOK here { http://bit.ly/2m77EgH } ......................................................................................................................... Download EPUB Ebook here { http://bit.ly/2m77EgH } ......................................................................................................................... Download doc Ebook here { http://bit.ly/2m77EgH } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book that can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer that is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story That Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money That the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths that Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Antworten 
    Sind Sie sicher, dass Sie …  Ja  Nein
    Ihre Nachricht erscheint hier
  • DOWNLOAD FULL BOOKS, INTO AVAILABLE FORMAT ......................................................................................................................... ......................................................................................................................... 1.DOWNLOAD FULL. PDF EBOOK here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. EPUB Ebook here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. doc Ebook here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. PDF EBOOK here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. EPUB Ebook here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. doc Ebook here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... ......................................................................................................................... ......................................................................................................................... .............. Browse by Genre Available eBooks ......................................................................................................................... Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult,
       Antworten 
    Sind Sie sicher, dass Sie …  Ja  Nein
    Ihre Nachricht erscheint hier
  • DOWNLOAD FULL BOOKS, INTO AVAILABLE FORMAT ......................................................................................................................... ......................................................................................................................... ,DOWNLOAD FULL. PDF EBOOK here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... ,DOWNLOAD FULL. EPUB Ebook here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... ,DOWNLOAD FULL. doc Ebook here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... ,DOWNLOAD FULL. PDF EBOOK here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... ,DOWNLOAD FULL. EPUB Ebook here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... ,DOWNLOAD FULL. doc Ebook here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... ......................................................................................................................... ......................................................................................................................... .............. Browse by Genre Available eBooks ......................................................................................................................... Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult,
       Antworten 
    Sind Sie sicher, dass Sie …  Ja  Nein
    Ihre Nachricht erscheint hier
  • DOWNLOAD FULL BOOKS, INTO AVAILABLE FORMAT ......................................................................................................................... ......................................................................................................................... 1.DOWNLOAD FULL. PDF EBOOK here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. EPUB Ebook here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. doc Ebook here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. PDF EBOOK here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. EPUB Ebook here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. doc Ebook here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... ......................................................................................................................... ......................................................................................................................... .............. Browse by Genre Available eBooks ......................................................................................................................... Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult,
       Antworten 
    Sind Sie sicher, dass Sie …  Ja  Nein
    Ihre Nachricht erscheint hier
  • Nice. thanks.
       Antworten 
    Sind Sie sicher, dass Sie …  Ja  Nein
    Ihre Nachricht erscheint hier

You Don't Know Query - WordCamp Portland 2011

  1. 1. WordCamp Portland 2011September 17, 2011
  2. 2. Andrew NacinCore Developer of WordPressTech Ninja at Audrey Capitalnacin@wordpress.org@nacin on Twitter
  3. 3. You Dont Know Query
  4. 4. What do you know?
  5. 5. Conditional Tagsis_author( ), is_home( ), etc.
  6. 6. Who has ever heard ofquery_posts( )?
  7. 7. Ways to queryquery_posts( )new WP_Query( )get_posts( )
  8. 8. The loopif ( have_posts( ) ) while ( have_posts( ) ) : the_post( ); endwhile( );
  9. 9. What dont you know?
  10. 10. Every query object has itsown methodsis_author( ) is the same as calling$wp_query->is_author( )
  11. 11. function is_author( ) { global $wp_query; return $wp_query->is_author( );}
  12. 12. If you do:$my_query = new WP_Query( $query );You can do:while ( $my_query->have_posts( ) ) : $my_query->the_post( );endwhile;wp_reset_postdata( );
  13. 13. But why do we call things likewp_reset_postdata( ) andwp_reset_query( )?What about using query_posts( )?How can you alter a query? Whatabout the main query?
  14. 14. What is the main query,and why should I care?
  15. 15. Lets dig in.
  16. 16. wp-blog-header.php// Load the WordPress bootstraprequire dirname( __FILE__ ) . /wp-load.php;// Do magicwp();// Decide which template files to loadABSPATH . WPINC . /template-loader.php;
  17. 17. Lets look in the bootstrap:$wp_the_query = new WP_Query();$wp_query =& $wp_the_query;
  18. 18. Quick lesson on PHP references$a = 4;$b =& $a;$b = 2;var_dump( $a ); // int(2)$a = 6;var_dump( $b ); // int(6)
  19. 19. So:So the real main query is in$wp_the_query.And a live copy of it is stored in$wp_query.
  20. 20. wp-blog-header.php// Load the WordPress bootstraprequire dirname( __FILE__ ) . /wp-load.php;// Do magicwp();// Decide which template files to loadABSPATH . WPINC . /template-loader.php;
  21. 21. wp-blog-header.php// Load the WordPress bootstraprequire dirname( __FILE__ ) . /wp-load.php;// Do magicwp( );// Decide which template files to loadABSPATH . WPINC . /template-loader.php;
  22. 22. What is that wp( ) call?function wp( $query_vars = ) { global $wp; $wp->main( $query_vars );}
  23. 23. Holy $!@?, what justhappened?
  24. 24. In the bootstrap:$wp = new WP( );So theres a wp( ) function,and a WP class.
  25. 25. class WP { . . . function main( ) { $this->init( ); $this->parse_request( ); $this->send_headers( ); $this->query_posts( ); $this->handle_404( ); $this->register_globals( ); . . .
  26. 26. class WP { . . . function main( ) { $this->init( ); $this->parse_request( ); $this->send_headers( ); $this->query_posts( ); $this->handle_404( ); $this->register_globals( ); . . .
  27. 27. WP::parse_request( )— Parses the URL using WP_Rewrite— Sets up query variables for WP_QueryWP::query_posts( ) { global $wp_the_query; $wp_the_query->query( $this->query_vars );}
  28. 28. Boom.SELECT SQL_CALC_FOUND_ROWS wp_posts.*FROM wp_postsWHERE 1=1 AND wp_posts.post_type = post AND wp_posts.post_status = publishORDER BY wp_posts.post_date DESCLIMIT 0, 10
  29. 29. wp-blog-header.php// Load WordPress.require dirname(__FILE__) . /wp-load.php;// Parse what to query, and query it.wp();// Load the theme.ABSPATH . WPINC . /template-loader.php;
  30. 30. Before we get to the theme,we have your posts.Got it?
  31. 31. Then why do we do this?query_posts( author=5 );get_header( );while( have_posts( ) ) : the_post( );endwhile;get_footer( );
  32. 32. Thats running 2* queries!One, the query WordPressthought we wanted.Two, this new one youreactually going to use.
  33. 33. * Actually, WP_Querydoesnt run just one query.It usually runs four.
  34. 34. 1. Get me my posts: SELECT SQL_CALC_FOUND_ROWS … FROM wp_posts LIMIT 0, 102. How many posts exist? SELECT FOUND_ROWS()3. Slurp all metadata for these posts.4. Slurp all terms for these posts.
  35. 35. PROTIP‘Measure twice, cut once’is bad for performance.
  36. 36. (A note, you can turn these off selectively…)$my_query = new WP_Query( array( no_found_rows => true, update_post_meta_cache => false, update_post_term_cache => false,) );
  37. 37. So. Instead of this:query_posts( author=5 );get_header( );while ( have_posts( ) ) : the_post( );endwhile;get_footer( );
  38. 38. We can use this:// In WP::parse_request()$this->query_vars = apply_filters( request, $this->query_vars );
  39. 39. We can modify queryvariables in mid air:function nacin_filter_out_author( $qvs ) { if ( ! isset( $qvs[author] ) ) $qvs[author] = -5; return $qvs;}
  40. 40. Powerful, but lacks context.
  41. 41. Powerful, but lacks context.Problem 1: Conditional tags dont work yet.
  42. 42. Powerful, but lacks context.Problem 1: Conditional tags dont work yet.Problem 2: Only works on the main query.
  43. 43. Powerful, but lacks context.Problem 1: Conditional tags dont work yet.Problem 2: Only works on the main query.Problem 3: WP_Query is waaay cooler.
  44. 44. Introducing pre_get_postsclass WP_Query { . . . function &get_posts() { $this->parse_query(); // Huzzah! Conditional tags are available. do_action_ref_array( pre_get_posts, array( &$this ) ); . . .
  45. 45. A truly awesome hook.function nacin_alter_home( $query ) { if ( $query->is_home( ) ) $query->set( author, -5 );}add_action( pre_get_posts, nacin_alter_home );
  46. 46. Still with us?Good, ‘cause here’s wherethings get hairy.
  47. 47. request fires for the main query only.pre_get_posts fires for every post query:— get_posts()— new WP_Query()— That random recent posts widget.— Everything.
  48. 48. What if I just want it on themain query?
  49. 49. $wp_the_query makes atriumphant return.
  50. 50. Main query only!function nacin_alter_home ( $query ) { if ( $wp_the_query === $query && $query->is_home() ) $query->set( author, -5 );}add_action( pre_get_posts, nacin_alter_home );
  51. 51. Hmm. How does this work?$wp_the_query should never be modified. Itholds the main query, forever.$wp_query keeps a live reference to$wp_the_query, unless you use query_posts().
  52. 52. query_posts( author=-5 );while ( have_posts( ) ) : the_post( );endwhile;wp_reset_query( );
  53. 53. query_posts( author=-5 );while ( have_posts( ) ) : the_post( );endwhile;wp_reset_query( );
  54. 54. class WP_Query { . . . function &query_posts( $query ) { // Break the reference to $wp_the_query unset( $wp_query ); $wp_query =& new WP_Query( $query ); . . .
  55. 55. query_posts( author=-5 );while ( have_posts( ) ) : the_post( );endwhile;wp_reset_query( );
  56. 56. class WP_Query { . . . function wp_reset_query( ) { // Restore the reference to$wp_the_query unset( $wp_query ); $wp_query =& $wp_the_query; // Reset the globals, too. wp_reset_postdata( ); . . .
  57. 57. Calling the_post( )? wp_reset_query( ) will reset $wp_query and and the globals.Calling $my_query->the_post( )? wp_reset_postdata( ) will reset the globals.
  58. 58. New thing for core in 3.3!Rather than: $wp_the_query === $other_query_object  Youll be able to call: $other_query_object->is_main_query( )  is_main_query( ), the function, will act on$wp_query, like any other conditional tag.
  59. 59. Some LessonsEvery WP_Query object has methods thatmimic the global conditional tags.The global conditional tags apply to$wp_query, the main or current query.$wp_query is always the main query, unlessyou use query_posts( ). Restore it withwp_reset_query( ).
  60. 60. And Finallyrequest is a nice hook. pre_get_posts is morepowerful and flexible. Just use it properly.Always check if youre modifying the main queryusing $query === $wp_the_query$query->is_main_query( ) in 3.3!
  61. 61. Thanks! Questions?@nacin

×