Skip to content

Instantly share code, notes, and snippets.

@birgire

birgire/field_query.php

Last active Jan 17, 2018
Embed
What would you like to do?
WordPress: Nested field queries - An idea for a plugin to support the "field_query" argument in the WP_Query class
<?php
/**
* Plugin Name: Field Query
* Description: Support the "field_query" argument in the WP_Query class
* Plugin URI: https://gist.github.com/birgire/ebf79ab6b12258a0e489
* Plugin Author: Birgir Erlendsson (birgire)
* Version: Proposal (2015-07-28)
**/
/**
* A plugin proposal to support the "field_query" argument in the WP_Query class
*
* It should support:
* - fields in the wp_posts table
* - nested queries (like tax_query and meta_query)
* - tax queries (tax_query using the WP_Tax_query class )
* - meta queries (meta_query using the WP_Meta_query class)
* - date queries (date_query using the WP_Date_query class)
* - comparition: =, <, >, !=, <>, <=, >=, LIKE, RLIKE, REGEXP
*/
Example 1
----------
$args =[
'field_query' => [
'outer_relation' => 'AND',
'relation' => 'OR',
[
'field' => 'title',
'value' => '%foo%',
'compare' => 'LIKE',
],
[
'field' => 'content',
'value' => '%foo%',
'compare' => 'LIKE',
],
]
];
Generated SQL:
{SQL FROM WP_Query} AND ( post_title LIKE '%foo%' OR post_content LIKE '%foo%' )
Example 2
----------
$args =[
'field_query' => [
'outer_relation' => 'OR',
'relation' => 'AND',
[
'field' => 'title',
'value' => '%foo%',
'compare' => 'LIKE',
],
[
'field' => 'ID',
'value' => '100',
'compare' => '>=',
],
]
];
Generated SQL:
{SQL FROM WP_Query} AND ( post_title LIKE '%foo%' AND ID >= 100 )
Example 3 (Nested)
----------
$args =[
'field_query' => [
'outer_relation' => 'AND',
'relation' => 'OR',
[
'relation' => 'AND',
[
'field' => 'title',
'value' => '%foo%',
'compare' => 'LIKE',
],
[
'field' => 'ID',
'value' => '100',
'compare' => '>=',
],
],
[
'relation' => 'AND',
[
'field' => 'title',
'value' => '%foo%',
'compare' => 'LIKE',
],
[
'field' => 'content',
'value' => '%foo%',
'compare' => 'LIKE',
],
]
]
];
Generated SQL:
{SQL FROM WP_Query} AND (
( post_title LIKE '%foo%' AND ID >= 100 )
OR
( post_title LIKE '%foo%' AND post_content LIKE '%foo%' )
)
Example 4 (with Tax Query)
----------
$args =[
'field_query' => [
'outer_relation' => 'AND',
'relation' => 'OR',
[
'field' => 'title',
'value' => '%foo%',
'compare' => 'LIKE',
],
[
'field' => 'content',
'value' => '%foo%',
'compare' => 'LIKE',
],
[
'field' => 'tax',
'tax_query' => [
[
'taxonomy' => 'category',
'field' => 'slug',
'terms' => 'foo',
]
]
],
]
];
Generated SQL:
{SQL FROM WP_Query} AND ( post_title LIKE '%foo%' OR post_content LIKE '%foo%' OR {TaxQuery} )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment