Using WordPress ‘meta_query_find_compatible_table_alias’ PHP filter

The meta_query_find_compatible_table_alias filter allows you to modify the table alias identified as compatible with the current clause in a WordPress meta query.

Usage

add_filter('meta_query_find_compatible_table_alias', function($alias, $clause, $parent_query, $query) {
    // your custom code here
    return $alias;
}, 10, 4);

Parameters

  • $alias (string|false) – The table alias or false if none was found.
  • $clause (array) – The first-order query clause.
  • $parent_query (array) – The parent of the $clause.
  • $query (WP_Meta_Query) – The WP_Meta_Query object.

More information

See WordPress Developer Resources: https://developer.wordpress.org/reference/hooks/meta_query_find_compatible_table_alias/

Examples

Change table alias for a custom table

In this example, we change the table alias for a custom table related to a specific meta key.

add_filter('meta_query_find_compatible_table_alias', function($alias, $clause, $parent_query, $query) {
    if ($clause['key'] === 'custom_meta_key') {
        // Change the alias to use a custom table
        $alias = 'custom_table_alias';
    }
    return $alias;
}, 10, 4);

Add a prefix to the table alias

In this example, we add a prefix to the table alias.

add_filter('meta_query_find_compatible_table_alias', function($alias, $clause, $parent_query, $query) {
    // Add a prefix to the table alias
    $alias = 'prefix_' . $alias;
    return $alias;
}, 10, 4);

Filter based on meta value type

In this example, we change the table alias based on the meta value type.

add_filter('meta_query_find_compatible_table_alias', function($alias, $clause, $parent_query, $query) {
    if ($clause['type'] === 'numeric') {
        // Change the alias for numeric meta values
        $alias = 'numeric_table_alias';
    }
    return $alias;
}, 10, 4);

Filter only on main query

In this example, we change the table alias only for the main query.

add_filter('meta_query_find_compatible_table_alias', function($alias, $clause, $parent_query, $query) {
    // Check if it is the main query
    if ($query->is_main_query()) {
        // Change the alias for the main query
        $alias = 'main_query_table_alias';
    }
    return $alias;
}, 10, 4);

Change alias based on the comparison operator

In this example, we change the table alias based on the comparison operator used in the meta query.

add_filter('meta_query_find_compatible_table_alias', function($alias, $clause, $parent_query, $query) {
    if ($clause['compare'] === 'LIKE') {
        // Change the alias for LIKE comparison
        $alias = 'like_table_alias';
    }
    return $alias;
}, 10, 4);