Using WordPress ‘get_tax_sql()’ PHP function

The get_tax_sql WordPress PHP function generates SQL to be appended to a main query, given a taxonomy query.

Usage

A generic example of using the function:

$tax_query = array(
  array(
    'taxonomy' => 'category',
    'field' => 'slug',
    'terms' => array('cat-a', 'cat-b'),
  )
);
global $wpdb;
$tax_sql = get_tax_sql($tax_query, $wpdb->posts, 'ID');

Parameters

  • $tax_query (array) – A compact tax query.
  • $primary_table (string) – The primary table to query.
  • $primary_id_column (string) – The primary ID column of the table.

More information

See WordPress Developer Resources: get_tax_sql

Examples

Filter posts by category

This example filters posts by categories with slugs ‘cat-a’ and ‘cat-b’:

$tax_query = array(
  array(
    'taxonomy' => 'category',
    'field' => 'slug',
    'terms' => array('cat-a', 'cat-b'),
  )
);
global $wpdb;
$tax_sql = get_tax_sql($tax_query, $wpdb->posts, 'ID');

Filter posts by tag

This example filters posts by tags with slugs ‘tag-1’ and ‘tag-2’:

$tax_query = array(
  array(
    'taxonomy' => 'post_tag',
    'field' => 'slug',
    'terms' => array('tag-1', 'tag-2'),
  )
);
global $wpdb;
$tax_sql = get_tax_sql($tax_query, $wpdb->posts, 'ID');

Filter posts with custom taxonomy

This example filters posts with a custom taxonomy called ‘my_taxonomy’ and terms with IDs 1 and 2:

$tax_query = array(
  array(
    'taxonomy' => 'my_taxonomy',
    'field' => 'term_id',
    'terms' => array(1, 2),
  )
);
global $wpdb;
$tax_sql = get_tax_sql($tax_query, $wpdb->posts, 'ID');

Filter posts by multiple taxonomies

This example filters posts that belong to both ‘category-1’ and ‘tag-1’:

$tax_query = array(
  'relation' => 'AND',
  array(
    'taxonomy' => 'category',
    'field' => 'slug',
    'terms' => 'category-1',
  ),
  array(
    'taxonomy' => 'post_tag',
    'field' => 'slug',
    'terms' => 'tag-1',
  )
);
global $wpdb;
$tax_sql = get_tax_sql($tax_query, $wpdb->posts, 'ID');

Filter posts by excluding terms

This example filters posts that do not belong to categories with IDs 3 and 4:

$tax_query = array(
  array(
    'taxonomy' => 'category',
    'field' => 'term_id',
    'terms' => array(3, 4),
    'operator' => 'NOT IN',
  )
);
global $wpdb;
$tax_sql = get_tax_sql($tax_query, $wpdb->posts, 'ID');