Using get_terms() with meta_query parameters

Inserting boolean term meta values

When we add non-existent term meta with e.g.

add_term_meta( 123, 'test', true );

then we are actually running the following insert :

$wpdb->insert( 'wp_termmeta', array(
   'term_id' => 123,
   'meta_key' => 'test',
   'meta_value' => true
) );

within the general add_metadata() function.

Now wpdb::insert() is actually a wrapper for wpdb::_insert_replace_helper()
that prepares the SQL insert query and maps the insert values to:

INSERT INTO `wp_termmeta` (`term_id`, `meta_key`, `meta_value`) VALUES (%d, %s, %s)

or in our test case:

INSERT INTO `wp_termmeta` (`term_id`, `meta_key`, `meta_value`) VALUES (123, 'test', '1')

Also note that the meta_value column is of longtext type in the wp_termmeta table.

So the boolean true is stored as the '1' string.

Fetching boolean term meta values

When get_terms() runs with this kind of meta query:

$args = array(
    'taxonomy'   => 'product_cat',
    'hide_empty' => false,
    'meta_query' => array(
         array(
            'key'       => 'featured',
            'value'     => true,
            'compare'   => '='
         )
    )
);

then the generated SQL query contains:

wp_termmeta.meta_key = 'featured' AND wp_termmeta.meta_value="1" 

where the true (bool) is converted to the '1' (string).

Leave a Comment