This is an update to a talk I gave three years ago at WordCamp Cape Town 2015. We’re at a point now where we have these incredibly powerful query classes in WordPress core that allow you to really tailor down to whatever criterion you want. In this talk, I take you through the outermost abstraction layers and deep into the SQL that WordPress actually uses to query for stuff on your site – it’s very much a “sky’s the limit” kind of situation.
Queries are really interesting and powerful, and a lot of people are intimidated by advanced queries, even with the abstraction layers that WordPress has put in place.
Getting Creative with WordPress QueriesDrewAPicture
We’re at a point now where we have these incredibly powerful query classes in WordPress core that allow you to really tailor down to whatever criterion you want. In this workshop, Drew will provide some real-world examples of some crazy stuff you can do with queries – it’s very much a “sky’s the limit” kind of situation. Queries are really interesting and powerful, and a lot of people are intimidated by advanced queries, even with the abstraction layers that WordPress has put in place.
https://speakerdeck.com/willroth/50-laravel-tricks-in-50-minutes - origin
Laravel 5.1 raised the bar for framework documentation, but there's much, much more lurking beneath the surface. In this 50-minute session, we'll explore 50 (yes, 50!) high-leverage implementation tips & tricks that you just won't find in the docs: the IoC Container, Blade, Eloquent, Middleware, Routing, Commands, Queues, Events, Caching — we'll cover them all! Join us as we drink from the fire hose & learn to take advantage of everything that Laravel has to offer to build better software faster!
This session is for those who are excited by the great power of Apache Solr search for Drupal and want to take things even further. Do you want take complete control over your search interface and offer more than the default features? Have you ever wondered what it takes to add data to your search index? Curious about defining facets, custom sorting, or making cool new widgets for filtering and faceting? Join us for a technical deep dive into the world of Solr search.
The general topics of this presentation will overlap with those covered at Drupalcon SF for the Drupal 6 version, but we will focus on use of the API as found in the Drupal 7 version.
Introducing the Solr index
* Learn about Solr fields, and how to map Drupal data onto them
* See how to add data to the search index
* Execute a search in PHP code and use the results
Using the API for custom search paths and interfaces
* How to use the prepare and alter hooks for the query object, and why they differ.
* Make use facing changes, or add filters that are transparent to the user.
Build custom facets based on node fields
* What comes OOTB
* Hooks to add facets for additional field types
Getting Creative with WordPress QueriesDrewAPicture
We’re at a point now where we have these incredibly powerful query classes in WordPress core that allow you to really tailor down to whatever criterion you want. In this workshop, Drew will provide some real-world examples of some crazy stuff you can do with queries – it’s very much a “sky’s the limit” kind of situation. Queries are really interesting and powerful, and a lot of people are intimidated by advanced queries, even with the abstraction layers that WordPress has put in place.
https://speakerdeck.com/willroth/50-laravel-tricks-in-50-minutes - origin
Laravel 5.1 raised the bar for framework documentation, but there's much, much more lurking beneath the surface. In this 50-minute session, we'll explore 50 (yes, 50!) high-leverage implementation tips & tricks that you just won't find in the docs: the IoC Container, Blade, Eloquent, Middleware, Routing, Commands, Queues, Events, Caching — we'll cover them all! Join us as we drink from the fire hose & learn to take advantage of everything that Laravel has to offer to build better software faster!
This session is for those who are excited by the great power of Apache Solr search for Drupal and want to take things even further. Do you want take complete control over your search interface and offer more than the default features? Have you ever wondered what it takes to add data to your search index? Curious about defining facets, custom sorting, or making cool new widgets for filtering and faceting? Join us for a technical deep dive into the world of Solr search.
The general topics of this presentation will overlap with those covered at Drupalcon SF for the Drupal 6 version, but we will focus on use of the API as found in the Drupal 7 version.
Introducing the Solr index
* Learn about Solr fields, and how to map Drupal data onto them
* See how to add data to the search index
* Execute a search in PHP code and use the results
Using the API for custom search paths and interfaces
* How to use the prepare and alter hooks for the query object, and why they differ.
* Make use facing changes, or add filters that are transparent to the user.
Build custom facets based on node fields
* What comes OOTB
* Hooks to add facets for additional field types
Hacking Your Way To Better Security - Dutch PHP Conference 2016Colin O'Dell
The goal of this talk is to educate developers on common security vulnerabilities, how they are exploited, and how to protect against them. We'll explore several of the OWASP Top 10 attack vectors like SQL injection, XSS, CSRF, session hijacking, and insecure direct object references. Each topic will be approached from the perspective of an attacker to see how these vulnerabilities are detected and exploited using several realistic examples. Once we've established an understanding of how these attacks work, we'll look at concrete steps you can take to secure web applications against such vulnerabilities. The knowledge gained from this talk can also be used for participating in "Capture the Flag" security competitions.
WP_Query, pre_get_posts, and eliminating query_posts()Erick Hitter
At the heart of WordPress is the WP_Query class, used to retrieve practically all content from the database and prepare it for display. In this presentation, I’ll discuss the myriad arguments available with WP_Query, the various properties and methods that are automatically populated, and the advanced queries made possible through filters within the class. I’ll also review the pre_get_posts action, detail how it can be used to modify standard WordPress queries and completely eliminate query_posts(), and explain why you’d want to do so in the first place.
You find a column named EntityNum in a table you manage, but what data belongs in this column? Not every detail of usage is clear from just SQL data type and constraints. What is the sensible range of values? Unit of measure? How is the column used by applications? Who in the world knows? We need a way to add comments to the database schema, just as we would write comments in application code to document how programmers should use it. But comments are useful only if they're correct and current, and if they're easy to read and to update. Schemadoc is an experimental tool to help in these goals.
In 2010, I told everyone how to start unit testing Zend Framework applications. In 2011, let’s take this a step further by testing services, work flows and performance. Looking to raise the bar on quality? Let this talk be the push you need to improve your Zend Framework projects.
Advanced PHP and MySQL : PHP/MySQL Functions, Integrating web forms and databases, Displaying queries in tables, Building Forms from queries, String and Regular Expressions, Sessions, Cookies and HTTP, E-Mail
MySQL 8 introduces support for ANSI SQL recursive queries with common table expressions, a powerful method for working with recursive data references. Until now, MySQL application developers have had to use workarounds for hierarchical data relationships. It's time to write SQL queries in a more standardized way, and be compatible with other brands of SQL implementations. But as always, the bottom line is: how does it perform? This presentation will briefly describe how to use recursive queries, and then test the performance and scalability of those queries against other solutions for hierarchical queries.
Scalability != performance. In fact, having to scale your architecture significantly with growth may be a symptom of a poor application performance. Yet, with the rise of cloud and the abundance of automation and container tools that simplify scalability aspect of your system, performance considerations are often pushed to the back row. Building systems for high performance is not easy. It requires a lot of considerations - from technology selection to design decisions. And "the cloud" does not magically solve those problems for you. In this talk I'll discuss common performance pitfalls across the stack and talk about useful techniques and examples that every application could benefit from.
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonfRafael Dohms
As developers we write code everyday, only to frown at it a week after that. Why do we have such a hard time with code written by others and ourselves, this raging desire to rewrite everything we see? Writing code that survives the test of time and self judgment is a matter of clarity and simplicity. Let's talk about growing, learning and improving our code with calisthenics, readability and good design.
We all know how to define database indexes, but which indexes to define remains a mysterious art for most software developers. This talk will use general principles and specific scenarios to give you practical, step-by-step knowledge to turn a performance bottleneck into an epic win!
How do you measure the quality of your code? Performance and testing are just one aspect of code, in order to meet deadlines and make maintenance quicker you also need your code to be readable, decoupled and generally easier to comprehend and work with. This talk will go over tips and exercises to help you identify trouble areas, refactor them and train you to write better code in future projects. Come make your code look and function better.
You Don't Know Query (WordCamp Netherlands 2012)andrewnacin
An update to a talk I gave at WordCamp Portland 2011, "You Don't Know Query" is an advanced development talk from March 25, 2012, in Utrecht, Netherlands.
Hacking Your Way To Better Security - Dutch PHP Conference 2016Colin O'Dell
The goal of this talk is to educate developers on common security vulnerabilities, how they are exploited, and how to protect against them. We'll explore several of the OWASP Top 10 attack vectors like SQL injection, XSS, CSRF, session hijacking, and insecure direct object references. Each topic will be approached from the perspective of an attacker to see how these vulnerabilities are detected and exploited using several realistic examples. Once we've established an understanding of how these attacks work, we'll look at concrete steps you can take to secure web applications against such vulnerabilities. The knowledge gained from this talk can also be used for participating in "Capture the Flag" security competitions.
WP_Query, pre_get_posts, and eliminating query_posts()Erick Hitter
At the heart of WordPress is the WP_Query class, used to retrieve practically all content from the database and prepare it for display. In this presentation, I’ll discuss the myriad arguments available with WP_Query, the various properties and methods that are automatically populated, and the advanced queries made possible through filters within the class. I’ll also review the pre_get_posts action, detail how it can be used to modify standard WordPress queries and completely eliminate query_posts(), and explain why you’d want to do so in the first place.
You find a column named EntityNum in a table you manage, but what data belongs in this column? Not every detail of usage is clear from just SQL data type and constraints. What is the sensible range of values? Unit of measure? How is the column used by applications? Who in the world knows? We need a way to add comments to the database schema, just as we would write comments in application code to document how programmers should use it. But comments are useful only if they're correct and current, and if they're easy to read and to update. Schemadoc is an experimental tool to help in these goals.
In 2010, I told everyone how to start unit testing Zend Framework applications. In 2011, let’s take this a step further by testing services, work flows and performance. Looking to raise the bar on quality? Let this talk be the push you need to improve your Zend Framework projects.
Advanced PHP and MySQL : PHP/MySQL Functions, Integrating web forms and databases, Displaying queries in tables, Building Forms from queries, String and Regular Expressions, Sessions, Cookies and HTTP, E-Mail
MySQL 8 introduces support for ANSI SQL recursive queries with common table expressions, a powerful method for working with recursive data references. Until now, MySQL application developers have had to use workarounds for hierarchical data relationships. It's time to write SQL queries in a more standardized way, and be compatible with other brands of SQL implementations. But as always, the bottom line is: how does it perform? This presentation will briefly describe how to use recursive queries, and then test the performance and scalability of those queries against other solutions for hierarchical queries.
Scalability != performance. In fact, having to scale your architecture significantly with growth may be a symptom of a poor application performance. Yet, with the rise of cloud and the abundance of automation and container tools that simplify scalability aspect of your system, performance considerations are often pushed to the back row. Building systems for high performance is not easy. It requires a lot of considerations - from technology selection to design decisions. And "the cloud" does not magically solve those problems for you. In this talk I'll discuss common performance pitfalls across the stack and talk about useful techniques and examples that every application could benefit from.
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonfRafael Dohms
As developers we write code everyday, only to frown at it a week after that. Why do we have such a hard time with code written by others and ourselves, this raging desire to rewrite everything we see? Writing code that survives the test of time and self judgment is a matter of clarity and simplicity. Let's talk about growing, learning and improving our code with calisthenics, readability and good design.
We all know how to define database indexes, but which indexes to define remains a mysterious art for most software developers. This talk will use general principles and specific scenarios to give you practical, step-by-step knowledge to turn a performance bottleneck into an epic win!
How do you measure the quality of your code? Performance and testing are just one aspect of code, in order to meet deadlines and make maintenance quicker you also need your code to be readable, decoupled and generally easier to comprehend and work with. This talk will go over tips and exercises to help you identify trouble areas, refactor them and train you to write better code in future projects. Come make your code look and function better.
You Don't Know Query (WordCamp Netherlands 2012)andrewnacin
An update to a talk I gave at WordCamp Portland 2011, "You Don't Know Query" is an advanced development talk from March 25, 2012, in Utrecht, Netherlands.
WordPress London 16 May 2012 - You don’t know queryl3rady
How to alter the main WordPress query the correct way. No more query_posts() pwease!
by Scott Cariss of Philosophy Design
Philosophy is a thought-led brand and digital consultancy based in London.
n 2010, I told everyone how to start unit testing Zend Framework applications. In 2011, let’s take this a step further by testing services, work flows and performance. Looking to raise the bar on quality? Let this talk be the push you need to improve your Zend Framework projects.
Supercharging WordPress Development - Wordcamp Brighton 2019Adam Tomat
Slide links:
- https://lumberjack.rareloop.com
- https://docs.lumberjack.rareloop.com
- https://github.com/Rareloop/lumberjack-bedrock-installer
- https://github.com/Rareloop/lumberjack
- https://github.com/Rareloop/lumberjack-validation
- https://github.com/Rareloop/hatchet
- rareloop.com/careers
- https://www.rareloop.com/posts/comparing-modern-mvc-wordpress-frameworks/
- https://lizkeogh.com/2017/08/31/reflecting-reality/amp
- https://www.youtube.com/watch?v=uQUxJObxTUs
- https://www.upstatement.com/timber
- https://roots.io/bedrock
---
Often WordPress themes are not easy to change, maintain or fun to work on. This can rule WordPress out as a viable option for bespoke, non-trivial websites.
In this talk we’ll dive into how this happens & look at how we can benefit from software engineering techniques to help make your code easier to change. I’ll also show how using Lumberjack, a powerful MVC framework built on Timber, can be used to power-up your themes.
WordPress currently powers over 1/5th of the internet and is growing. Historically, people think of WordPress as a blogging platform or use it as a CMS, but can this tool known and used by millions of people also be used to create complex applications? WordPress is familiar, easy to use, actively developed and supported, and has a powerful codebase that allows one to quickly develop applications and websites. These things make WordPress a great option to develop you next application. We will walk through examples of WordPress's use to create applications and very complex sites and then dive into the internals of WordPress that make this happen including: Custom Data Types, WordPress Hooks, Database Interactions, Connecting to Remote APIs, The WordPress JSON API, Caching, Extensibility, User and Role Management, Templates, and URL Rewriting.
This is my speech at PHPDAY2011
WordPress for developers:
WordPress features overview
Custom type and Taxonomy
Routing and rewrite rules
Custom query and manipulation
Cache tips
Debugging tools
WordPress Development in a Modern PHP WorldDrewAPicture
WordPress’ minimum-supported version is still PHP 5.2 (gasp!) but that doesn’t mean you should let that hold you back from leveraging modern PHP features in your plugins and themes!
In this talk, we’ll take a deep dive into ways you can start leveraging modern PHP features today to bring new life to that old plugin or theme. We’ll cover how to code partial plugin activation for old versions of PHP, use autoloaders and namespaces, setup group aliasing, use return type declarations, leverage traits, and much more.
How to Win Friends and Influence WordPress CoreDrewAPicture
Presented at WordCamp Portland, September 23, 2017.
It’s no secret that one of the WordPress core team’s greatest barriers to entry is contributors feeling like they don’t have anything of value to offer; nothing could be further from the truth.
Every potential contributor has something to offer whether they realize it or not, and this session will give them many of the tools and advice they’ll need to succeed in helping to influence the future of WordPress.
Topics covered: entry points for contributors of all levels, whether they’re developers, designers, copywriters, or everyday users. We’ll briefly cover the process of joining the “Making WordPress” community, methods to have your voice heard, submitting patches and keeping trac tickets moving, bringing core down to the local community level, and more.
This talk encompasses the idea that each of us can be empowered to use and improve WordPress through beta testing of upcoming releases. The 4.4 release is set to hit Beta 1 just three days before WCPDX, which makes this talk a unique opportunity to educate WordCampers on the value of beta testing, and even to interactively participate in testing the next version of WordPress during the talk. I’ll cover my personal journey and lessons learned in dogfooding WordPress for a living, as well as ways anyone (yes, anyone) can get started testing with little to no barrier to entry.
In this session, Drew will be sharing insight into how a WordPress release happens, including an overview of all the moving parts, teams, organization, and execution. A lot of people have this idea that the core team is solely responsible for new versions of WordPress getting released, which couldn’t be further from the truth – it’s an intricate ballet of multiple contributor teams coming together and executing a broad vision.
He will talk about how a release cycle is structured, how and where the decision-making happens, as well as all of the various contributors and teams that play their own part in a successful release. It’s very much opening the black box of how a release works.
Setting Up WordPress: A NUX Case StudyDrewAPicture
This topic was presented at WordCamp Europe 2015 in Seville, Spain.
Synopsis:
Once you’ve installed WordPress, what now? For new users, that’s just one of a multitude of inevitable questions. What’s a post? A page? A theme? Where should I start first? In a short attention-span world, first impressions are everything, and WordPress is making it harder than it needs to be for new users.
There’s a case to be made for helping to guide users through the process of post-install set up. In fact, there’s user testing data that makes the case for us.
The goal of this talk is to examine that test data – taken against existing and potential wp-admin flows – and form conclusions about how WordPress can get out of its own way to improve the new user experience. We’ll talk about solutions that exist in the community right now, and opportunities to get involved in reshaping WordPress’ first impressions.
Core Docs: Sentencing WordPress to 11-years-to-lifeDrewAPicture
Core docs extend far beyond maintaining dated Codex pages and writing inline comments. In fact, even the way core code is written is a contributor to core documentation. And in all the ways we contribute docs, we need to ensure they stand the test of time.
This talk takes a stroll through the docs roadmap devised Summer 2013 and how that’s progressing. We’ll examine the diminished role the Codex will take going forward, as well as highlight some exciting initiatives coming into the fold — including the handbooks, code reference, and more.
Putting the (docs) Cart Before the (standards) HorseDrewAPicture
Slides for my Write the Docs presentation, May 6, 2014 in Portland. Presentation abstract here: http://docs.writethedocs.org/2014/na/talks/#drew-jaynes-putting-the-docs-cart-before-the-standards-horse
A review of the growth of the Israel Genealogy Research Association Database Collection for the last 12 months. Our collection is now passed the 3 million mark and still growing. See which archives have contributed the most. See the different types of records we have, and which years have had records added. You can also see what we have for the future.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
Normal Labour/ Stages of Labour/ Mechanism of LabourWasim Ak
Normal labor is also termed spontaneous labor, defined as the natural physiological process through which the fetus, placenta, and membranes are expelled from the uterus through the birth canal at term (37 to 42 weeks
Francesca Gottschalk - How can education support child empowerment.pptxEduSkills OECD
Francesca Gottschalk from the OECD’s Centre for Educational Research and Innovation presents at the Ask an Expert Webinar: How can education support child empowerment?
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
7. The Loop
if ( have_posts() ) :
while ( have_posts() ) :
the_post();
...
endwhile;
endif;
8. The Loop: Internals
if ( $wp_query->have_posts() ) :
while ( $wp_query->have_posts() ) :
$wp_query->the_post();
...
endwhile;
endif;
9. WP_Query
// Query for the 7 latest, published posts.
$query = new WP_Query( array(
'posts_per_page' => 7,
'post_status' => 'publish'
) );
10. WP_Query: SQL
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts
WHERE 1=1
AND wp_posts.post_type = 'post'
AND wp_posts.post_status = 'publish'
ORDER BY wp_posts.post_date DESC
LIMIT 0, 7
11. • WP_Query wrapper
• Defaults: Filter suppression
• Defaults: No sticky posts
• Defaults: No found rows
• Array of results vs WP_Query instance
get_posts()
12. get_posts()
// Query for the 7 latest published posts.
$query = get_posts( array(
'posts_per_page' => 7,
'post_status' => 'publish'
) );
13. get_posts(): SQL
SELECT wp_posts.ID FROM wp_posts
WHERE 1=1
AND wp_posts.post_type = 'post'
AND wp_posts.post_status = 'publish'
ORDER BY wp_posts.post_date DESC
LIMIT 0, 7
14. WP_Query: SQL
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts
WHERE 1=1
AND wp_posts.post_type = 'post'
AND wp_posts.post_status = 'publish'
ORDER BY wp_posts.post_date DESC
LIMIT 0, 7
15. • Action, not a filter
• $wp_query passed by reference
• Fires before the query actually runs
• Use query methods like $query->is_main_query()
• is_main_query() === _doing_it_wrong()
pre_get_posts
16. pre_get_posts
/**
* Display both posts and pages in the home loop.
*
* @param WP_Query $query Main WP_Query instance.
*/
function pages_in_main_query( $query ) {
if ( ! is_admin() && is_home() ) {
$query->query_vars['post_type'] = array( 'post', 'page' );
}
}
add_action( 'pre_get_posts', 'pages_in_main_query' );
17. pre_get_posts: Original SQL
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts
WHERE 1=1
AND wp_posts.post_type = 'post'
AND (
wp_posts.post_status = ‘publish'
)
ORDER BY wp_posts.post_date DESC
LIMIT 0, 10
18. pre_get_posts: New SQL
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts
WHERE 1=1
AND wp_posts.post_type IN ( 'post', 'page' )
AND (
wp_posts.post_status = ‘publish'
)
ORDER BY wp_posts.post_date DESC
LIMIT 0, 10
20. • Completely overrides the main query
• Very few valid use cases
• Can break pagination (and other stuff)
• wp_reset_query()
• Don’t use it
query_posts()
31. WP_Query multiple orderby: SQL
SELECT wp_posts.ID FROM wp_posts
WHERE 1=1
AND wp_posts.post_type = 'post'
AND wp_posts.post_status = 'publish'
ORDER BY wp_posts.post_date DESC, wp_posts.post_title ASC
LIMIT 0, 15
32. • Order by independent, named meta clauses
• WP_Meta_Query, WP_User_Query,
WP_Comment_Query
WP_Query orderby: meta clauses
34. WP_Query orderby: SQL
SELECT wp_posts.ID FROM wp_posts
INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )
INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id )
WHERE 1=1
AND (
( wp_postmeta.meta_key = ‘state’
AND CAST( wp_postmeta.meta_value AS CHAR ) = ‘Colorado'
)
AND mt1.meta_key = ‘city'
)
AND wp_posts.post_type = 'post'
AND ( ( wp_posts.post_status = 'publish' ) )
GROUP BY wp_posts.ID
ORDER BY
CAST( mt1.meta_value AS CHAR ) ASC,
CAST( wp_postmeta.meta_value AS CHAR ) DESC
LIMIT 0, 5
36. WP_User_Query registered on Tuesday
// Query for users registered on a Tuesday.
$query = new WP_User_Query( array(
‘count_total' => false,
‘orderby' => ‘display_name’,
'date_query' => array(
array(
'column' => 'user_registered',
'dayofweek' => 3 // Tuesday
)
),
) );
37. WP_User_Query registered on Tuesday: SQL
SELECT wp_users.*.ID FROM wp_users
WHERE 1=1
AND (
DAYOFWEEK( wp_users.user_registered ) = 3
)
ORDER BY
display_name ASC
38. WP_User_Query lifetime value
// Query for top 10 customers with a lifetime value 1,000+
$query = new WP_User_Query( array(
‘number’ => 10,
‘count_total’ => false, // No pagination.
‘meta_query’ => array(
‘lifetime_value’ => array(
‘key’ => ‘lifetime_value’,
‘compare’ => ‘>=’,
‘value’ => 1000,
‘type’ => ‘DECIMAL’,
),
),
// Order by lifetime value high to low, then name A-Z
'orderby' => array(
‘lifetime_value’ => ‘DESC’,
‘name’ => ‘ASC’,
) );
39. WP_User_Query lifetime value: SQL
SELECT wp_users.*.ID FROM wp_users
INNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id )
WHERE 1=1
AND (
wp_usermeta.meta_key = ‘lifetime_value’
AND CAST( wp_usermeta.meta_value AS DECIMAL >= ‘1000’ )
ORDER BY
CAST( wp_usermeta.meta_value AS DECIMAL ) DESC,
display_name ASC
LIMIT 0, 10
42. WP_Term_Query name__like: SQL
SELECT t.name FROM wp_terms AS t
INNER JOIN wp_term_taxonomy AS tt ON t.term_id = tt.term_id
WHERE
tt.taxonomy IN (‘mascots’) AND t.name LIKE ‘%monster%'
ORDER BY t.name ASC
LIMIT 6
44. • Order results by a value in a custom table
• Adds an additional LEFT JOIN
WP_Query orderby with custom tables
45. Joining Custom Tables: JOIN
/**
* Join vote totals table to the 'books' custom post type query.
*
* @param string $join JOIN query clauses.
* @param WP_Query $query Current WP_Query instance.
* @return string The filtered JOIN clauses.
*/
function join_votes_table( $join, $query ) {
global $wpdb;
if ( ! is_admin() ) {
if ( isset( $query->query_vars['post_type'] )
&& 'books' == $query->query_vars[‘post_type']
) {
$votes = $wpdb->prefix . 'up_down_post_vote_totals';
$join .= "LEFT JOIN $votes ON $wpdb->posts.ID = $votes.post_id ";
}
}
return $join;
}
add_filter( 'posts_join', 'join_votes_table', 10, 2 );
46. Joining Custom Tables: ORDERBY
/**
* Order by vote totals descending, then post date descending.
*
* @param string $orderby ORDER BY query clauses.
* @param WP_Query $query Current WP_Query instance.
* @return string The filtered ORDER BY query clauses.
*/
function orderby_votes_and_date( $orderby, $query ) {
global $wpdb;
if ( ! is_admin() ) {
if ( isset( $query->query_vars['post_type'] )
&& 'books' == $query->query_vars[‘post_type']
) {
$votes = $wpdb->prefix . 'up_down_post_vote_totals';
$orderby = "$votes.vote_count_up DESC, $wpdb->posts.post_date DESC";
}
}
return $orderby;
}
add_filter( 'posts_orderby', 'orderby_votes_and_date', 10, 2 );
47. Joining Custom Tables: Original SQL
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts
WHERE 1=1
AND wp_posts.post_type = 'books'
AND (
wp_posts.post_status = ‘publish'
OR wp_posts.post_status = ‘private'
)
ORDER BY wp_posts.post_date DESC
LIMIT 0, 10
48. Joining Custom Tables: SQL with JOIN
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts
LEFT JOIN wp_up_down_post_vote_totals
ON wp_posts.ID = wp_up_down_post_vote_totals.post_id
WHERE 1=1
AND wp_posts.post_type = 'books'
AND (
wp_posts.post_status = ‘publish'
OR wp_posts.post_status = ‘private'
)
ORDER BY
wp_up_down_post_vote_totals.vote_count_up DESC,
wp_posts.post_date DESC
LIMIT 0, 10