SlideShare une entreprise Scribd logo
1  sur  24
Télécharger pour lire hors ligne
Parsing Strange:
   URL to SQL to HTML
                          Hal Stern
                 snowmanonfire.com      headshot by Richard Stevens
                                        http://dieselsweeties.com

           slideshare.net/freeholdhal

    © 2010 Hal Stern
Some Rights Reserved
Why Do You Care?
•    Database performance = user experience
•    A little database expertise goes a long way
•    Taxonomies for more than sidebar lists
•    Custom post types (!!)
•    WordPress is a powerful CMS
      > Change default behaviors
      > Defy the common wisdom
      > Integrate other content sources/filters
    © 2010 Hal Stern
Some Rights Reserved                WordCamp Boulder   2
Flow of Control
•  Web server URL manipulation
      > Real file or permalink URL?
•  URL to query variables
      > What to display? Tag? Post? Category?
•  Query variables to SQL generation
      > How exactly to get that content?
•  Template file selection
      > How will content be displayed?
•  Content manipulation

    © 2010 Hal Stern
Some Rights Reserved                  WordCamp Boulder   3
Whose File Is This?
•  User URL request passed to web server
•  Web server checks
   .htaccess file    <IfModule mod_rewrite.c>
                     RewriteEngine On
                              RewriteBase   /whereyouputWordPress/
      > WP install root       RewriteCond   %{REQUEST_FILENAME} !-f
                              RewriteCond   %{REQUEST_FILENAME} !-d
      > Other .htaccess       RewriteRule
                              </IfModule>
                                            . /index.php [L]

        files may interfere
•  Basic rewriting rules:
   If file or directory URL doesn’t exist, start
   WordPress via index.php
    © 2010 Hal Stern
Some Rights Reserved                   WordCamp Boulder               4
Example Meta Fail: 404 Not Found
myblog/
myblog/wp-content (etc)
myblog/images


•  Access broken image URLs for
   unintended results: no 404 pages!
   myblog/images/not-a-pic.jpg!
•  Web server can’t find file, assumes it’s a
   permalink, hands to WP
•  WP can’t interpret it, so defaults to home
    © 2010 Hal Stern
Some Rights Reserved         WordCamp Boulder   5
What Happens Before The Loop
•    Parse URL into a query
•    Set conditionals & select templates
•    Execute the query & cache results
•    Run the Loop:
     <?php
     if (have_posts()) :
        while (have_posts()) :
         the_post();
         //loop content
        endwhile;
     endif;
     ?>

    © 2010 Hal Stern
Some Rights Reserved             WordCamp Boulder   6
Examining the Query String
<?php
   global $wp_query;
   echo ”SQL for this page ";
   echo $wp_query->request;
   echo "<br>";
?>


•  SQL passed to MySQL in WP_Query
   object’s request element
•  Brute force: edit theme footer.php	
  to
   see main loop’s query for displayed page
    © 2010 Hal Stern
Some Rights Reserved            WordCamp Boulder   7
“Home Page” Query Deconstruction

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' OR
 wp_posts.post_status = 'private’)
ORDER BY wp_posts.post_date DESC LIMIT 0, 10


Get all fields from posts table, but limit number of returned rows

Only get posts, and those that are published or private to the user

Sort the results by date in descending order

Start results starting with record 0 and up to 10 more results



    © 2010 Hal Stern
Some Rights Reserved                               WordCamp Boulder   8
Query Parsing
•  parse_request() method of WP_Query
   extracts query variables from URL
•  Execute rewrite rules
      > Pick off ?p=67 style http GET variables
      > Match permalink structure
      > Match keywords like “author” and “tag”
      > Match custom post type slugs


    © 2010 Hal Stern
Some Rights Reserved              WordCamp Boulder   9
Query Variables to SQL
•  Query type: post by title, posts by category
   or tag, posts by date
•  Variables for the query
      > Slug values for category/tags
      > Month/day numbers
      > Explicit variable values
        ?p=67 for post_id
•  post_type variable has been around for
   a while; CPT fill in new values
    © 2010 Hal Stern
Some Rights Reserved               WordCamp Boulder   10
Simple Title Slug Parsing
/2010/premio-sausage




     SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND YEAR
     (wp_posts.post_date)='2010' AND wp_posts.post_name = 'premio-
     sausage' AND wp_posts.post_type = 'post' ORDER BY
     wp_posts.post_date DESC

•  Rewrite matches root of permalink,
   extracts tail of URL as a title slug

    © 2010 Hal Stern
Some Rights Reserved                      WordCamp Boulder           11
Graphs and JOIN Operations
•  WordPress treats tags and categories as
   “terms”, mapped 1:N to posts
•  Relational databases aren’t ideal for this
      > INNER JOIN builds intermediate tables on
        common key values
•  Following link in a social graph is
   equivalent to an INNER JOIN on tables of
   linked items

    © 2010 Hal Stern
Some Rights Reserved             WordCamp Boulder   12
WordPress Taxonomy Tables

wp_posts               wp_term_relationships      wp_term_taxonomy
post_id                object_id                  term_taxonomy_id
….                     term_taxonomy_id           term_id
post_date                                         taxonomy
…                                                 description
post_content


•  Term relationships table maps
   N:1 terms to each post                         wp_terms
                                                  term_id
•  Term taxonomy maps slugs                       name
   1:N to taxonomies                              slug
•  Term table has slugs for URL
   mapping
    © 2010 Hal Stern
Some Rights Reserved                           WordCamp Boulder      13
Taxonomy Lookup
  /tag/premio




SELECT SQL_CALC_FOUND_ROWS wp_posts.* FROM wp_posts
INNER JOIN wp_term_relationships ON
(wp_posts.ID = wp_term_relationships.object_id)
INNER JOIN wp_term_taxonomy ON
  (wp_term_relationships.term_taxonomy_id =
   wp_term_taxonomy.term_taxonomy_id)
INNER JOIN wp_terms ON
   (wp_term_taxonomy.term_id = wp_terms.term_id)
WHERE 1=1 AND wp_term_taxonomy.taxonomy = 'post_tag' AND wp_terms.slug IN
('premio') AND wp_posts.post_type = 'post' AND (wp_posts.post_status =
'publish' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER
BY wp_posts.post_date DESC LIMIT 0, 10

    © 2010 Hal Stern
Some Rights Reserved                           WordCamp Boulder             14
More on Canonical URLs
•  Canonical URLs improve SEO
•  WordPress is really good about generating
   301 Redirects for non-standard URLs
•  Example: URL doesn’t appear to match a
   permalink, WordPress does prediction
      > Use “LIKE title%” in WHERE clause
      > Matches “title” as initial substring with %
        wildcard

    © 2010 Hal Stern
Some Rights Reserved                WordCamp Boulder   15
Modifying the Query
•  Brute force isn’t necessarily good
      > Using query_posts() ignores all previous
        parsing, runs a new SQL query
•  Filter query_vars
      > Change default parsing (convert any day to a
        week’s worth of posts, for example)
•  Actions parse_query & parse_request
      > Access WP_Query object before execution
      > is_xx() conditionals are already set

    © 2010 Hal Stern
Some Rights Reserved              WordCamp Boulder   16
SQL Generation Filters
•  posts_where
      > More explicit control over query variable to
        SQL grammar mapping
•  posts_join
      > Add or modify JOINS for other graph like
        relationships
•  Many other filters
      > Change grouping of results
      > Change ordering of results

    © 2010 Hal Stern
Some Rights Reserved                 WordCamp Boulder   17
Custom Post Types
•  Change SQL WHERE clause on post type
      > wp_posts.post_type=‘ebay’
•  Add new rewrite rules for URL parsing similar
   to category & tag
      > Set slug in CPT registration array
           'rewrite' => array ("slug" => “ebay”),
•  Watch out for competing, overwritten or
   unflushed rewrite entries
    <?php echo "<pre>”;
    print_r(get_option('rewrite_rules'));
    echo "</pre>”;
    ?>
    © 2010 Hal Stern
Some Rights Reserved                 WordCamp Boulder   18
Applications
•  Stylized listings
      > Category sorted alphabetically
      > Use posts as listings of resources (jobs,
        clients, events) – good CPT application
•  Custom URL slugs
      > Add rewrite rules to match slug and set query
        variables
•  Joining other social graphs
      > Suggested/related content

    © 2010 Hal Stern
Some Rights Reserved                WordCamp Boulder   19
Template File Selection
•  is_x() conditionals set in query parsing
•  Used to drive template selection
      > is_tag() looks for tag-slug, tag-id, then tag
      > Full search hierarchy in Codex
•  template_redirect action
      > Called in the template loader
      > Add actions to override defaults


    © 2010 Hal Stern
Some Rights Reserved               WordCamp Boulder   20
HTML Generation
•  Done in the_post() method
•  Raw content retrieved from MySQL
      > Short codes interpreted
      > CSS applied
•  Some caching plugins generate and store
   HTML, so YMMV



    © 2010 Hal Stern
Some Rights Reserved              WordCamp Boulder   21
Why Do You Care?
•  User experience improvement
      > JOINS are expensive
      > Large table, repetitive SELECTs = slow
      > Running query once keeps cache warm
      > Category, permalink, title slug choices matter
•  More CMS, less “blog”
      > Alphabetical sort
      > Adding taxonomy/social graph elements

    © 2010 Hal Stern
Some Rights Reserved               WordCamp Boulder      22
Resources

•  Core files where SQL stuff happens
      > query.php
      > post.php
      > canonical.php
      > rewrite.php
•  Template	
  loader	
  search	
  path	
  
      >  http://codex.wordpress.org/Template_Hierarchy



    © 2010 Hal Stern
Some Rights Reserved                      WordCamp Boulder   23
Contact

Hal Stern
freeholdhal@gmail.com
@freeholdhal
snowmanonfire.com
facebook.com/hal.stern

slideshare.net/freeholdhal




    © 2010 Hal Stern
Some Rights Reserved         WordCamp Boulder   24

Contenu connexe

Tendances

Using Apache Solr
Using Apache SolrUsing Apache Solr
Using Apache Solrpittaya
 
Solr Recipes Workshop
Solr Recipes WorkshopSolr Recipes Workshop
Solr Recipes WorkshopErik Hatcher
 
Dspace configuration on XMLUI DSpace
Dspace configuration on XMLUI DSpaceDspace configuration on XMLUI DSpace
Dspace configuration on XMLUI DSpaceBharat Chaudhari
 
Building Intelligent Search Applications with Apache Solr and PHP5
Building Intelligent Search Applications with Apache Solr and PHP5Building Intelligent Search Applications with Apache Solr and PHP5
Building Intelligent Search Applications with Apache Solr and PHP5israelekpo
 
Solr 6 Feature Preview
Solr 6 Feature PreviewSolr 6 Feature Preview
Solr 6 Feature PreviewYonik Seeley
 
Introduction to Solr
Introduction to SolrIntroduction to Solr
Introduction to SolrErik Hatcher
 
Introduction to Apache Solr.
Introduction to Apache Solr.Introduction to Apache Solr.
Introduction to Apache Solr.ashish0x90
 
Parsing strange v1.1
Parsing strange v1.1Parsing strange v1.1
Parsing strange v1.1Hal Stern
 
Find Anything In Your APEX App - Fuzzy Search with Oracle Text
Find Anything In Your APEX App - Fuzzy Search with Oracle TextFind Anything In Your APEX App - Fuzzy Search with Oracle Text
Find Anything In Your APEX App - Fuzzy Search with Oracle TextCarsten Czarski
 
Beyond full-text searches with Lucene and Solr
Beyond full-text searches with Lucene and SolrBeyond full-text searches with Lucene and Solr
Beyond full-text searches with Lucene and SolrBertrand Delacretaz
 
Lessons from a Dying CMS
Lessons from a Dying CMSLessons from a Dying CMS
Lessons from a Dying CMSSandy Smith
 
Deepak khetawat sling_models_sightly_jsp
Deepak khetawat sling_models_sightly_jspDeepak khetawat sling_models_sightly_jsp
Deepak khetawat sling_models_sightly_jspDEEPAK KHETAWAT
 
A JCR View of the World - adaptTo() 2012 Berlin
A JCR View of the World - adaptTo() 2012 BerlinA JCR View of the World - adaptTo() 2012 Berlin
A JCR View of the World - adaptTo() 2012 BerlinAlexander Klimetschek
 
Introduction to Apache solr
Introduction to Apache solrIntroduction to Apache solr
Introduction to Apache solrKnoldus Inc.
 
Intro to Apache Solr for Drupal
Intro to Apache Solr for DrupalIntro to Apache Solr for Drupal
Intro to Apache Solr for DrupalChris Caple
 

Tendances (20)

Using Apache Solr
Using Apache SolrUsing Apache Solr
Using Apache Solr
 
Solr Recipes Workshop
Solr Recipes WorkshopSolr Recipes Workshop
Solr Recipes Workshop
 
Apache Solr Workshop
Apache Solr WorkshopApache Solr Workshop
Apache Solr Workshop
 
Dspace configuration on XMLUI DSpace
Dspace configuration on XMLUI DSpaceDspace configuration on XMLUI DSpace
Dspace configuration on XMLUI DSpace
 
Wizard of ORDS
Wizard of ORDSWizard of ORDS
Wizard of ORDS
 
Apache Solr
Apache SolrApache Solr
Apache Solr
 
Building Intelligent Search Applications with Apache Solr and PHP5
Building Intelligent Search Applications with Apache Solr and PHP5Building Intelligent Search Applications with Apache Solr and PHP5
Building Intelligent Search Applications with Apache Solr and PHP5
 
Solr 6 Feature Preview
Solr 6 Feature PreviewSolr 6 Feature Preview
Solr 6 Feature Preview
 
Introduction to Solr
Introduction to SolrIntroduction to Solr
Introduction to Solr
 
Introduction to Apache Solr.
Introduction to Apache Solr.Introduction to Apache Solr.
Introduction to Apache Solr.
 
Solr Presentation
Solr PresentationSolr Presentation
Solr Presentation
 
Parsing strange v1.1
Parsing strange v1.1Parsing strange v1.1
Parsing strange v1.1
 
Find Anything In Your APEX App - Fuzzy Search with Oracle Text
Find Anything In Your APEX App - Fuzzy Search with Oracle TextFind Anything In Your APEX App - Fuzzy Search with Oracle Text
Find Anything In Your APEX App - Fuzzy Search with Oracle Text
 
Beyond full-text searches with Lucene and Solr
Beyond full-text searches with Lucene and SolrBeyond full-text searches with Lucene and Solr
Beyond full-text searches with Lucene and Solr
 
Introduction to Apache Solr
Introduction to Apache SolrIntroduction to Apache Solr
Introduction to Apache Solr
 
Lessons from a Dying CMS
Lessons from a Dying CMSLessons from a Dying CMS
Lessons from a Dying CMS
 
Deepak khetawat sling_models_sightly_jsp
Deepak khetawat sling_models_sightly_jspDeepak khetawat sling_models_sightly_jsp
Deepak khetawat sling_models_sightly_jsp
 
A JCR View of the World - adaptTo() 2012 Berlin
A JCR View of the World - adaptTo() 2012 BerlinA JCR View of the World - adaptTo() 2012 Berlin
A JCR View of the World - adaptTo() 2012 Berlin
 
Introduction to Apache solr
Introduction to Apache solrIntroduction to Apache solr
Introduction to Apache solr
 
Intro to Apache Solr for Drupal
Intro to Apache Solr for DrupalIntro to Apache Solr for Drupal
Intro to Apache Solr for Drupal
 

En vedette

Parsing strange v3
Parsing strange v3Parsing strange v3
Parsing strange v3Hal Stern
 
Ogra S1 2010 Op Competitiveness Part1
Ogra S1 2010 Op Competitiveness Part1Ogra S1 2010 Op Competitiveness Part1
Ogra S1 2010 Op Competitiveness Part1Veselina Nikolova
 
Shades team in action
Shades team in actionShades team in action
Shades team in actionDonna Roberts
 
Stephen 205 (1)
Stephen 205 (1)Stephen 205 (1)
Stephen 205 (1)farsiya
 
Stephen Rathinaraj Corr
Stephen Rathinaraj   CorrStephen Rathinaraj   Corr
Stephen Rathinaraj Corrfarsiya
 
Entr sme10 the_secret_of_success_-_the_many_faces_of_european_entrepreneurshi...
Entr sme10 the_secret_of_success_-_the_many_faces_of_european_entrepreneurshi...Entr sme10 the_secret_of_success_-_the_many_faces_of_european_entrepreneurshi...
Entr sme10 the_secret_of_success_-_the_many_faces_of_european_entrepreneurshi...Veselina Nikolova
 
Teoria de control presentacion
Teoria de control presentacionTeoria de control presentacion
Teoria de control presentacioncesar
 
100512074 analisis-de-respuesta-transitoria-docx
100512074 analisis-de-respuesta-transitoria-docx100512074 analisis-de-respuesta-transitoria-docx
100512074 analisis-de-respuesta-transitoria-docxcesar
 

En vedette (14)

Faces all
Faces allFaces all
Faces all
 
Parsing strange v3
Parsing strange v3Parsing strange v3
Parsing strange v3
 
Ogra S1 2010 Op Competitiveness Part1
Ogra S1 2010 Op Competitiveness Part1Ogra S1 2010 Op Competitiveness Part1
Ogra S1 2010 Op Competitiveness Part1
 
11 13
11 1311 13
11 13
 
Presentation sofia
Presentation sofiaPresentation sofia
Presentation sofia
 
Ogra s3-2010 success
Ogra s3-2010 successOgra s3-2010 success
Ogra s3-2010 success
 
ЕГДБ
ЕГДБЕГДБ
ЕГДБ
 
Ogra s4-2010 tenders
Ogra s4-2010 tendersOgra s4-2010 tenders
Ogra s4-2010 tenders
 
Shades team in action
Shades team in actionShades team in action
Shades team in action
 
Stephen 205 (1)
Stephen 205 (1)Stephen 205 (1)
Stephen 205 (1)
 
Stephen Rathinaraj Corr
Stephen Rathinaraj   CorrStephen Rathinaraj   Corr
Stephen Rathinaraj Corr
 
Entr sme10 the_secret_of_success_-_the_many_faces_of_european_entrepreneurshi...
Entr sme10 the_secret_of_success_-_the_many_faces_of_european_entrepreneurshi...Entr sme10 the_secret_of_success_-_the_many_faces_of_european_entrepreneurshi...
Entr sme10 the_secret_of_success_-_the_many_faces_of_european_entrepreneurshi...
 
Teoria de control presentacion
Teoria de control presentacionTeoria de control presentacion
Teoria de control presentacion
 
100512074 analisis-de-respuesta-transitoria-docx
100512074 analisis-de-respuesta-transitoria-docx100512074 analisis-de-respuesta-transitoria-docx
100512074 analisis-de-respuesta-transitoria-docx
 

Similaire à Parsing strange v2

The WordPress University 2012
The WordPress University 2012The WordPress University 2012
The WordPress University 2012Stephanie Leary
 
Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...
Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...
Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...Lucidworks
 
PHP and MySQL.pptx
PHP and MySQL.pptxPHP and MySQL.pptx
PHP and MySQL.pptxnatesanp1234
 
Modeling Tricks My Relational Database Never Taught Me
Modeling Tricks My Relational Database Never Taught MeModeling Tricks My Relational Database Never Taught Me
Modeling Tricks My Relational Database Never Taught MeDavid Boike
 
Wordpress theme development
Wordpress theme developmentWordpress theme development
Wordpress theme developmentNaeem Junejo
 
Advancing Your Custom Fields - WordCamp 2014
Advancing Your Custom Fields - WordCamp 2014Advancing Your Custom Fields - WordCamp 2014
Advancing Your Custom Fields - WordCamp 2014Carleton Web Services
 
Best Practices for WordPress
Best Practices for WordPressBest Practices for WordPress
Best Practices for WordPressTaylor Lovett
 
Carrington Core (2014)
Carrington Core (2014)Carrington Core (2014)
Carrington Core (2014)alexkingorg
 
Customizing the SharePoint 2013 user interface with JavaScript - Chris OBrien
Customizing the SharePoint 2013 user interface with JavaScript - Chris OBrienCustomizing the SharePoint 2013 user interface with JavaScript - Chris OBrien
Customizing the SharePoint 2013 user interface with JavaScript - Chris OBrienChris O'Brien
 
Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019Adam Tomat
 
What's New in WordPress 3.0 (for developers)
What's New in WordPress 3.0 (for developers)What's New in WordPress 3.0 (for developers)
What's New in WordPress 3.0 (for developers)Stephanie Leary
 
Launching a WordPress Site 101 (Cincinnati WordPress, August 2015)
Launching a WordPress Site 101 (Cincinnati WordPress, August 2015)Launching a WordPress Site 101 (Cincinnati WordPress, August 2015)
Launching a WordPress Site 101 (Cincinnati WordPress, August 2015)Andrew Duthie
 
Salesforce Development Best Practices
Salesforce Development Best PracticesSalesforce Development Best Practices
Salesforce Development Best PracticesVivek Chawla
 
SilverStripe From a Developer's Perspective
SilverStripe From a Developer's PerspectiveSilverStripe From a Developer's Perspective
SilverStripe From a Developer's Perspectiveajshort
 
Learning to run
Learning to runLearning to run
Learning to rundominion
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP TutorialLorna Mitchell
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsCarol McDonald
 
Essentials for the SharePoint Power User - SharePoint Engage Raleigh 2017
Essentials for the SharePoint Power User - SharePoint Engage Raleigh 2017Essentials for the SharePoint Power User - SharePoint Engage Raleigh 2017
Essentials for the SharePoint Power User - SharePoint Engage Raleigh 2017Drew Madelung
 

Similaire à Parsing strange v2 (20)

The WordPress University 2012
The WordPress University 2012The WordPress University 2012
The WordPress University 2012
 
&lt;?php + WordPress
&lt;?php + WordPress&lt;?php + WordPress
&lt;?php + WordPress
 
Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...
Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...
Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...
 
PHP and MySQL.pptx
PHP and MySQL.pptxPHP and MySQL.pptx
PHP and MySQL.pptx
 
Modeling Tricks My Relational Database Never Taught Me
Modeling Tricks My Relational Database Never Taught MeModeling Tricks My Relational Database Never Taught Me
Modeling Tricks My Relational Database Never Taught Me
 
Wordpress theme development
Wordpress theme developmentWordpress theme development
Wordpress theme development
 
Advancing Your Custom Fields - WordCamp 2014
Advancing Your Custom Fields - WordCamp 2014Advancing Your Custom Fields - WordCamp 2014
Advancing Your Custom Fields - WordCamp 2014
 
Best Practices for WordPress
Best Practices for WordPressBest Practices for WordPress
Best Practices for WordPress
 
Carrington Core (2014)
Carrington Core (2014)Carrington Core (2014)
Carrington Core (2014)
 
Customizing the SharePoint 2013 user interface with JavaScript - Chris OBrien
Customizing the SharePoint 2013 user interface with JavaScript - Chris OBrienCustomizing the SharePoint 2013 user interface with JavaScript - Chris OBrien
Customizing the SharePoint 2013 user interface with JavaScript - Chris OBrien
 
Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019
 
What's New in WordPress 3.0 (for developers)
What's New in WordPress 3.0 (for developers)What's New in WordPress 3.0 (for developers)
What's New in WordPress 3.0 (for developers)
 
Launching a WordPress Site 101 (Cincinnati WordPress, August 2015)
Launching a WordPress Site 101 (Cincinnati WordPress, August 2015)Launching a WordPress Site 101 (Cincinnati WordPress, August 2015)
Launching a WordPress Site 101 (Cincinnati WordPress, August 2015)
 
Salesforce Development Best Practices
Salesforce Development Best PracticesSalesforce Development Best Practices
Salesforce Development Best Practices
 
SilverStripe From a Developer's Perspective
SilverStripe From a Developer's PerspectiveSilverStripe From a Developer's Perspective
SilverStripe From a Developer's Perspective
 
Learning to run
Learning to runLearning to run
Learning to run
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
Rest
RestRest
Rest
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 
Essentials for the SharePoint Power User - SharePoint Engage Raleigh 2017
Essentials for the SharePoint Power User - SharePoint Engage Raleigh 2017Essentials for the SharePoint Power User - SharePoint Engage Raleigh 2017
Essentials for the SharePoint Power User - SharePoint Engage Raleigh 2017
 

Dernier

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 

Dernier (20)

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 

Parsing strange v2

  • 1. Parsing Strange: URL to SQL to HTML Hal Stern snowmanonfire.com headshot by Richard Stevens http://dieselsweeties.com slideshare.net/freeholdhal © 2010 Hal Stern Some Rights Reserved
  • 2. Why Do You Care? •  Database performance = user experience •  A little database expertise goes a long way •  Taxonomies for more than sidebar lists •  Custom post types (!!) •  WordPress is a powerful CMS > Change default behaviors > Defy the common wisdom > Integrate other content sources/filters © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 2
  • 3. Flow of Control •  Web server URL manipulation > Real file or permalink URL? •  URL to query variables > What to display? Tag? Post? Category? •  Query variables to SQL generation > How exactly to get that content? •  Template file selection > How will content be displayed? •  Content manipulation © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 3
  • 4. Whose File Is This? •  User URL request passed to web server •  Web server checks .htaccess file <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /whereyouputWordPress/ > WP install root RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d > Other .htaccess RewriteRule </IfModule> . /index.php [L] files may interfere •  Basic rewriting rules: If file or directory URL doesn’t exist, start WordPress via index.php © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 4
  • 5. Example Meta Fail: 404 Not Found myblog/ myblog/wp-content (etc) myblog/images •  Access broken image URLs for unintended results: no 404 pages! myblog/images/not-a-pic.jpg! •  Web server can’t find file, assumes it’s a permalink, hands to WP •  WP can’t interpret it, so defaults to home © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 5
  • 6. What Happens Before The Loop •  Parse URL into a query •  Set conditionals & select templates •  Execute the query & cache results •  Run the Loop: <?php if (have_posts()) : while (have_posts()) : the_post(); //loop content endwhile; endif; ?> © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 6
  • 7. Examining the Query String <?php global $wp_query; echo ”SQL for this page "; echo $wp_query->request; echo "<br>"; ?> •  SQL passed to MySQL in WP_Query object’s request element •  Brute force: edit theme footer.php  to see main loop’s query for displayed page © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 7
  • 8. “Home Page” Query Deconstruction 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' OR wp_posts.post_status = 'private’) ORDER BY wp_posts.post_date DESC LIMIT 0, 10 Get all fields from posts table, but limit number of returned rows Only get posts, and those that are published or private to the user Sort the results by date in descending order Start results starting with record 0 and up to 10 more results © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 8
  • 9. Query Parsing •  parse_request() method of WP_Query extracts query variables from URL •  Execute rewrite rules > Pick off ?p=67 style http GET variables > Match permalink structure > Match keywords like “author” and “tag” > Match custom post type slugs © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 9
  • 10. Query Variables to SQL •  Query type: post by title, posts by category or tag, posts by date •  Variables for the query > Slug values for category/tags > Month/day numbers > Explicit variable values ?p=67 for post_id •  post_type variable has been around for a while; CPT fill in new values © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 10
  • 11. Simple Title Slug Parsing /2010/premio-sausage SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND YEAR (wp_posts.post_date)='2010' AND wp_posts.post_name = 'premio- sausage' AND wp_posts.post_type = 'post' ORDER BY wp_posts.post_date DESC •  Rewrite matches root of permalink, extracts tail of URL as a title slug © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 11
  • 12. Graphs and JOIN Operations •  WordPress treats tags and categories as “terms”, mapped 1:N to posts •  Relational databases aren’t ideal for this > INNER JOIN builds intermediate tables on common key values •  Following link in a social graph is equivalent to an INNER JOIN on tables of linked items © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 12
  • 13. WordPress Taxonomy Tables wp_posts wp_term_relationships wp_term_taxonomy post_id object_id term_taxonomy_id …. term_taxonomy_id term_id post_date taxonomy … description post_content •  Term relationships table maps N:1 terms to each post wp_terms term_id •  Term taxonomy maps slugs name 1:N to taxonomies slug •  Term table has slugs for URL mapping © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 13
  • 14. Taxonomy Lookup /tag/premio SELECT SQL_CALC_FOUND_ROWS wp_posts.* FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id) INNER JOIN wp_terms ON (wp_term_taxonomy.term_id = wp_terms.term_id) WHERE 1=1 AND wp_term_taxonomy.taxonomy = 'post_tag' AND wp_terms.slug IN ('premio') AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 10 © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 14
  • 15. More on Canonical URLs •  Canonical URLs improve SEO •  WordPress is really good about generating 301 Redirects for non-standard URLs •  Example: URL doesn’t appear to match a permalink, WordPress does prediction > Use “LIKE title%” in WHERE clause > Matches “title” as initial substring with % wildcard © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 15
  • 16. Modifying the Query •  Brute force isn’t necessarily good > Using query_posts() ignores all previous parsing, runs a new SQL query •  Filter query_vars > Change default parsing (convert any day to a week’s worth of posts, for example) •  Actions parse_query & parse_request > Access WP_Query object before execution > is_xx() conditionals are already set © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 16
  • 17. SQL Generation Filters •  posts_where > More explicit control over query variable to SQL grammar mapping •  posts_join > Add or modify JOINS for other graph like relationships •  Many other filters > Change grouping of results > Change ordering of results © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 17
  • 18. Custom Post Types •  Change SQL WHERE clause on post type > wp_posts.post_type=‘ebay’ •  Add new rewrite rules for URL parsing similar to category & tag > Set slug in CPT registration array 'rewrite' => array ("slug" => “ebay”), •  Watch out for competing, overwritten or unflushed rewrite entries <?php echo "<pre>”; print_r(get_option('rewrite_rules')); echo "</pre>”; ?> © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 18
  • 19. Applications •  Stylized listings > Category sorted alphabetically > Use posts as listings of resources (jobs, clients, events) – good CPT application •  Custom URL slugs > Add rewrite rules to match slug and set query variables •  Joining other social graphs > Suggested/related content © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 19
  • 20. Template File Selection •  is_x() conditionals set in query parsing •  Used to drive template selection > is_tag() looks for tag-slug, tag-id, then tag > Full search hierarchy in Codex •  template_redirect action > Called in the template loader > Add actions to override defaults © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 20
  • 21. HTML Generation •  Done in the_post() method •  Raw content retrieved from MySQL > Short codes interpreted > CSS applied •  Some caching plugins generate and store HTML, so YMMV © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 21
  • 22. Why Do You Care? •  User experience improvement > JOINS are expensive > Large table, repetitive SELECTs = slow > Running query once keeps cache warm > Category, permalink, title slug choices matter •  More CMS, less “blog” > Alphabetical sort > Adding taxonomy/social graph elements © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 22
  • 23. Resources •  Core files where SQL stuff happens > query.php > post.php > canonical.php > rewrite.php •  Template  loader  search  path   >  http://codex.wordpress.org/Template_Hierarchy © 2010 Hal Stern Some Rights Reserved WordCamp Boulder 23