SlideShare une entreprise Scribd logo
1  sur  53
You Don’t Know Query

 WordCamp Edinburgh UK
     14-15 July 2012
Scott Cariss aka Brady
• Lead developer at Philosophy Design.

• Moderator at WordPress Answers
  (http://wordpress.stackexchange.com)

• WordPress plugin developer and enthusiast

scott@philosophydesign.com
@l3rady on Twitter
You Don’t Know Query
What do you know?
Conditional Tags
is_author(), is_home(), etc.
Who has ever heard of query_posts()?
Ways to query
query_posts()
new WP_Query()
get_posts()
The loop
if( have_posts() )
   while( have_posts() ):
     the_post();

  endwhile();
What don’t you know?
Every query object has its own
               methods
is_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( ); endwhile;
wp_reset_postdata( );
But why do we call things like
wp_reset_postdata( ) and
wp_reset_query( )?

What about using query_posts( )?

How can you alter a query? What about
the main query?
What is the main query, and why
         should I care?




     Let's dig in
wp-blog-header.php
// Load the WordPress bootstrap require
dirname( __FILE__ ) . '/wp-load.php';




// Decide which template files to load
ABSPATH . WPINC . '/template-loader.php';
Let’s 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:
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 bootstrap require
dirname( __FILE__ ) . '/wp-load.php';

// Do magic
wp();

// Decide which template files to load
ABSPATH . WPINC . '/template-loader.php';
What is that wp() call?
function wp( $query_vars = '' )
{
  global $wp;

    $wp->main( $query_vars );
}
Holy $!@?, what just happened?
In the bootstrap:
$wp = new WP()

So there’s a wp() function, and a WP class.
class WP
{
  ...
  function main( )
  {
      $this->init( );
      $this->parse_request( );
      $this->send_headers( );
      $this->query_posts( );
      $this->handle_404( );
      $this->register_globals( );
  }
  ...
}
class WP
{
  ...
  function main( )
  {
      $this->init( );
      $this->parse_request( );
      $this->send_headers( );
      $this->query_posts( );
      $this->handle_404( );
      $this->register_globals( );
  }
  ...
}
WP::parse_request( )
Parses the URL using WP_Rewrite
Sets up query variables for WP_Query

WP::query_posts( )
{
  global $wp_the_query;
  $wp_the_query->query( $this->query_vars );
}
What do we get?
SELECT SQL_CALC_FOUND_ROWS
  wp_posts.* 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, 10
wp-blog-header.php
// Load WordPress
dirname( __FILE__ ) . '/wp-load.php';

// Parse what to query, and query it.
wp();

// Load the theme.
ABSPATH . WPINC . '/template-loader.php';
Before we get to the theme, we have
             your posts.
Are we clear so far?
Then why do we do this?
query_posts( 'author=5' );
get_header( );

while( have_posts( ) ) :
  the_post( );
endwhile;

get_footer( );
That’s running 2* queries!
One, the query WordPress
thought we wanted.

Two, this new one you’re
actually going to use.
* Actually, WP_Query doesn't run just one
query. It usually runs four.
1. Get me my posts: SELECT
     SQL_CALC_FOUND_ROWS …
     FROM wp_posts LIMIT 0, 10
2. How many posts exist?
     SELECT FOUND_ROWS()
3. Pull down all metadata for these posts.
4. Pull down all terms for these posts.
Instead of query_posts()?
We can use this:

// In WP::parse_request()

$this->query_vars = apply_filters(
  'request', $this->query_vars );
We can modify query variables in mid
               air:
function brady_filter_out_author( $qvs )
{
  if( ! Isset( $qvs*‘author’+ ) )
     $qvs*‘author’+ = ‘-5’;

  return $qvs;
}
add_filter( “request”, “brady_filter_out_author”);
Powerful, but lacks context.
Problems:

1. Conditional tags don’t work yet.

2. Only works on the main query.

3. WP_Query is way cooler.
Introducing pre_get_posts
class WP_Query
{
   ...
   function &get_posts()
   {
     $this->parse_query();
     // OMG! Conditional tags are available!!
     do_action_ref_array( 'pre_get_posts', array( &$this ) );
   }
   ...
}
Lets kill off query_posts()!
function brady_alter_home( $query )
{
  if ( $query->is_home( ) )
     $query->set( 'author', '-5' );
}
add_action(
  'pre_get_posts', ‘brady_alter_home' );
Still with us?
Good ‘cause here’s where things get hairy.
‘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.
What if I just want it on the
       main query?
$wp_the_query makes a
  triumphant return.
Main query only!
function brady_alter_home( $query )
{
  if ( $query->is_home( ) &&
        $wp_the_query === $query )
     $query->set( 'author', '-5' );
}
add_action(
  'pre_get_posts', ‘brady_alter_home' );
Hmm. How does this work?
$wp_the_query should never be modified. It
 holds the main query, forever.

$wp_query keeps a live reference to
 $wp_the_query, unless you use query_posts().
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( $wp_query );
       $wp_query =& new WP_Query( $query );
       ...
   }
   ...
}
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
      unset( $wp_query );
      $wp_query =& $wp_the_query;
      // Reset the globals, too.
      wp_reset_postdata( );
      ...
  }
  ....
}
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.
Since WordPress 3.3!
Rather than:
$wp_the_query === $other_query_object

You‘re able to call:
$other_query_object->is_main_query( )
Some Lessons
Every WP_Query object has methods that mimic
  the global conditional tags.

The global conditional tags apply to
  $wp_query, the main or current query.

$wp_query is always the main query, unless you
 use query_posts( ). Restore it with
 wp_reset_query( ).
And finally
request is a nice hook. pre_get_posts is more
  powerful and flexible. Just use it properly.

Always check if you're modifying the main query
  using $query->is_main_query( )

$query === $wp_the_query before 3.3
Demo
Thank you! Any questions?

Contenu connexe

Tendances

Getting Creative with WordPress Queries, Again
Getting Creative with WordPress Queries, AgainGetting Creative with WordPress Queries, Again
Getting Creative with WordPress Queries, AgainDrewAPicture
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2zfconfua
 
購物車程式架構簡介
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介Jace Ju
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in actionJace Ju
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в MagentoMagecom Ukraine
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPDifference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPVineet Kumar Saini
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony TechniquesKris Wallsmith
 
Caching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment CachingCaching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment CachingErick Hitter
 
Plugin jQuery, Design Patterns
Plugin jQuery, Design PatternsPlugin jQuery, Design Patterns
Plugin jQuery, Design PatternsRobert Casanova
 
jQuery Plugin Creation
jQuery Plugin CreationjQuery Plugin Creation
jQuery Plugin Creationbenalman
 
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
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, 2018Balázs Tatár
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
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()
WP_Query, pre_get_posts, and eliminating query_posts()Erick Hitter
 
Let's write secure Drupal code! - Drupal Camp Poland 2019
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
 

Tendances (20)

Getting Creative with WordPress Queries, Again
Getting Creative with WordPress Queries, AgainGetting Creative with WordPress Queries, Again
Getting Creative with WordPress Queries, Again
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2
 
購物車程式架構簡介
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
 
Hooks WCSD12
Hooks WCSD12Hooks WCSD12
Hooks WCSD12
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
 
WCLV13 JavaScript
WCLV13 JavaScriptWCLV13 JavaScript
WCLV13 JavaScript
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPDifference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
 
Current state-of-php
Current state-of-phpCurrent state-of-php
Current state-of-php
 
Advanced Django
Advanced DjangoAdvanced Django
Advanced Django
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
CodeIgniter 3.0
CodeIgniter 3.0CodeIgniter 3.0
CodeIgniter 3.0
 
Lithium Best
Lithium Best Lithium Best
Lithium Best
 
Caching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment CachingCaching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment Caching
 
Plugin jQuery, Design Patterns
Plugin jQuery, Design PatternsPlugin jQuery, Design Patterns
Plugin jQuery, Design Patterns
 
jQuery Plugin Creation
jQuery Plugin CreationjQuery Plugin Creation
jQuery Plugin Creation
 
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
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
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
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()
WP_Query, pre_get_posts, and eliminating query_posts()
 
Let's write secure Drupal code! - Drupal Camp Poland 2019
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
 

Similaire à You don’t know query - WordCamp UK Edinburgh 2012

Working with WP_Query in WordPress
Working with WP_Query in WordPressWorking with WP_Query in WordPress
Working with WP_Query in WordPresstopher1kenobe
 
Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?Yevhen Kotelnytskyi
 
[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018Adam Tomat
 
Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Yevhen Kotelnytskyi
 
Becoming a better WordPress Developer
Becoming a better WordPress DeveloperBecoming a better WordPress Developer
Becoming a better WordPress DeveloperJoey Kudish
 
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)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)Mike Schinkel
 
Can WordPress really do that? A case study of vierderduer.no
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
 
Custom Database Queries in WordPress
Custom Database Queries in WordPressCustom Database Queries in WordPress
Custom Database Queries in WordPresstopher1kenobe
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 
Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019Adam Tomat
 
[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress DevelopmentAdam Tomat
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)arcware
 
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014Cliff Seal
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overviewjsmith92
 
Laying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme developmentLaying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme developmentTammy Hart
 
WordPress as an application framework
WordPress as an application frameworkWordPress as an application framework
WordPress as an application frameworkDustin Filippini
 
Apostrophe
ApostropheApostrophe
Apostrophetompunk
 

Similaire à You don’t know query - WordCamp UK Edinburgh 2012 (20)

Working with WP_Query in WordPress
Working with WP_Query in WordPressWorking with WP_Query in WordPress
Working with WP_Query in WordPress
 
Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?
 
[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018
 
Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0
 
Becoming a better WordPress Developer
Becoming a better WordPress DeveloperBecoming a better WordPress Developer
Becoming a better WordPress Developer
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
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)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
 
Can WordPress really do that? A case study of vierderduer.no
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
 
Custom Database Queries in WordPress
Custom Database Queries in WordPressCustom Database Queries in WordPress
Custom Database Queries in WordPress
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019
 
[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development
 
php2.pptx
php2.pptxphp2.pptx
php2.pptx
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
 
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
 
QA for PHP projects
QA for PHP projectsQA for PHP projects
QA for PHP projects
 
Laying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme developmentLaying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme development
 
WordPress as an application framework
WordPress as an application frameworkWordPress as an application framework
WordPress as an application framework
 
Apostrophe
ApostropheApostrophe
Apostrophe
 

Dernier

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 

Dernier (20)

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

You don’t know query - WordCamp UK Edinburgh 2012

  • 1. You Don’t Know Query WordCamp Edinburgh UK 14-15 July 2012
  • 2. Scott Cariss aka Brady • Lead developer at Philosophy Design. • Moderator at WordPress Answers (http://wordpress.stackexchange.com) • WordPress plugin developer and enthusiast scott@philosophydesign.com @l3rady on Twitter
  • 4. What do you know?
  • 6. Who has ever heard of query_posts()?
  • 7. Ways to query query_posts() new WP_Query() get_posts()
  • 8. The loop if( have_posts() ) while( have_posts() ): the_post(); endwhile();
  • 10. Every query object has its own methods is_author() is the same as calling $wp_query->is_author()
  • 11. function is_author() { global $wp_query; return $wp_query->is_author(); }
  • 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. But why do we call things like wp_reset_postdata( ) and wp_reset_query( )? What about using query_posts( )? How can you alter a query? What about the main query?
  • 14. What is the main query, and why should I care? Let's dig in
  • 15. wp-blog-header.php // Load the WordPress bootstrap require dirname( __FILE__ ) . '/wp-load.php'; // Decide which template files to load ABSPATH . WPINC . '/template-loader.php';
  • 16. Let’s look in the bootstrap: $wp_the_query = new WP_Query(); $wp_query =& $wp_the_query;
  • 17. Quick lesson on PHP references $a = 4; $b =& $a; $b = 2; var_dump( $a ); // int(2) $a = 6; var_dump( $b ); // int(6)
  • 18. So: The real main query is in $wp_the_query. And a live copy of it is stored in $wp_query
  • 19. wp-blog-header.php // Load the WordPress bootstrap require dirname( __FILE__ ) . '/wp-load.php'; // Do magic wp(); // Decide which template files to load ABSPATH . WPINC . '/template-loader.php';
  • 20. What is that wp() call? function wp( $query_vars = '' ) { global $wp; $wp->main( $query_vars ); }
  • 21. Holy $!@?, what just happened?
  • 22. In the bootstrap: $wp = new WP() So there’s a wp() function, and a WP class.
  • 23. class WP { ... function main( ) { $this->init( ); $this->parse_request( ); $this->send_headers( ); $this->query_posts( ); $this->handle_404( ); $this->register_globals( ); } ... }
  • 24. class WP { ... function main( ) { $this->init( ); $this->parse_request( ); $this->send_headers( ); $this->query_posts( ); $this->handle_404( ); $this->register_globals( ); } ... }
  • 25. WP::parse_request( ) Parses the URL using WP_Rewrite Sets up query variables for WP_Query WP::query_posts( ) { global $wp_the_query; $wp_the_query->query( $this->query_vars ); }
  • 26. What do we get? SELECT SQL_CALC_FOUND_ROWS wp_posts.* 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, 10
  • 27. wp-blog-header.php // Load WordPress dirname( __FILE__ ) . '/wp-load.php'; // Parse what to query, and query it. wp(); // Load the theme. ABSPATH . WPINC . '/template-loader.php';
  • 28. Before we get to the theme, we have your posts. Are we clear so far?
  • 29. Then why do we do this? query_posts( 'author=5' ); get_header( ); while( have_posts( ) ) : the_post( ); endwhile; get_footer( );
  • 30. That’s running 2* queries! One, the query WordPress thought we wanted. Two, this new one you’re actually going to use.
  • 31. * Actually, WP_Query doesn't run just one query. It usually runs four.
  • 32. 1. Get me my posts: SELECT SQL_CALC_FOUND_ROWS … FROM wp_posts LIMIT 0, 10 2. How many posts exist? SELECT FOUND_ROWS() 3. Pull down all metadata for these posts. 4. Pull down all terms for these posts.
  • 33. Instead of query_posts()? We can use this: // In WP::parse_request() $this->query_vars = apply_filters( 'request', $this->query_vars );
  • 34. We can modify query variables in mid air: function brady_filter_out_author( $qvs ) { if( ! Isset( $qvs*‘author’+ ) ) $qvs*‘author’+ = ‘-5’; return $qvs; } add_filter( “request”, “brady_filter_out_author”);
  • 35. Powerful, but lacks context. Problems: 1. Conditional tags don’t work yet. 2. Only works on the main query. 3. WP_Query is way cooler.
  • 36. Introducing pre_get_posts class WP_Query { ... function &get_posts() { $this->parse_query(); // OMG! Conditional tags are available!! do_action_ref_array( 'pre_get_posts', array( &$this ) ); } ... }
  • 37. Lets kill off query_posts()! function brady_alter_home( $query ) { if ( $query->is_home( ) ) $query->set( 'author', '-5' ); } add_action( 'pre_get_posts', ‘brady_alter_home' );
  • 38. Still with us? Good ‘cause here’s where things get hairy.
  • 39. ‘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.
  • 40. What if I just want it on the main query?
  • 41. $wp_the_query makes a triumphant return.
  • 42. Main query only! function brady_alter_home( $query ) { if ( $query->is_home( ) && $wp_the_query === $query ) $query->set( 'author', '-5' ); } add_action( 'pre_get_posts', ‘brady_alter_home' );
  • 43. Hmm. How does this work? $wp_the_query should never be modified. It holds the main query, forever. $wp_query keeps a live reference to $wp_the_query, unless you use query_posts().
  • 44. query_posts( 'author=-5' ); while ( have_posts( ) ) : the_post( ); endwhile; wp_reset_query( );
  • 45. class WP_Query { ... function &query_posts( $query ) { // Break the reference to $wp_the_query unset( $wp_query ); $wp_query =& new WP_Query( $query ); ... } ... }
  • 46. query_posts( 'author=-5' ); while ( have_posts( ) ) : the_post( ); endwhile; wp_reset_query( );
  • 47. 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( ); ... } .... }
  • 48. 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.
  • 49. Since WordPress 3.3! Rather than: $wp_the_query === $other_query_object You‘re able to call: $other_query_object->is_main_query( )
  • 50. Some Lessons Every WP_Query object has methods that mimic the global conditional tags. The global conditional tags apply to $wp_query, the main or current query. $wp_query is always the main query, unless you use query_posts( ). Restore it with wp_reset_query( ).
  • 51. And finally request is a nice hook. pre_get_posts is more powerful and flexible. Just use it properly. Always check if you're modifying the main query using $query->is_main_query( ) $query === $wp_the_query before 3.3
  • 52. Demo
  • 53. Thank you! Any questions?