Make WordPress Core

Opened 7 years ago

Last modified 7 years ago

#39632 new feature request

Adding Query identifier attribute

Reported by: prosti's profile prosti Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: Query Keywords:
Focuses: ui Cc:

Description (last modified by SergeyBiryukov)

You create any query by passing the arguments to WP_Query.
What will happen if we add the custom query identifier _id like this?

$args = array(
  '_id' => 'custom_name',
$q = new WP_Query( $args );

Nothing bad, and one good thing.

Using this _id I can work with filters like posts_where super easy.
This would work for many other filters from wp-includes/class-wp-query.php

function _20170118_posts_where( $where,  \WP_Query $q ){
  // $q->query will hold the query arguments ...
  if ( 'custom_name' == $q->query['_id'] ){
    // do our improvement on $where 
    return $where.
 return $where;

add_filter( 'posts_where', '_20170118_posts_where', 10 , 2 );

If you need more details here is the original example.

This already works, but we can benefit more if we add the _id for all WordPress core generated queries?

This should happen just after WP_Rewrite returns the query arguments, based on the query flags.

Let's test the future in case of main search query ( $is_search flag is true ).

You may write like this to address the search query:

add_filter( 'posts_where', function ( $where, \WP_Query $q ) {
  if( ! is_admin() && $q->is_main_query() && $q->is_search() ){
  ... // do something with $where
return $where;

but with the _id main-search argument, you could write:

add_filter( 'posts_where', function ( $where, \WP_Query $q ) {
  if ( 'main-search' == $q->get( '_id' ) ){
  ... // do something with $where
return $where;

This is somehow similar to the threads #15063 and #23833, but not exactly.

What would be the gain?

WordPress query programming may become simpler, and queries may be managed using human-readable names.

Change History (2)

#1 @SergeyBiryukov
7 years ago

  • Description modified (diff)

#2 @johnbillion
7 years ago

  • Version trunk deleted
Note: See TracTickets for help on using tickets.