0

I have a custom taxonomy with custom meta. I have added the custom meta values to columns in the admin list page just fine. But if I search for values that are in these columns nothing is found. I'm assuming I need to use pre_get_terms, but am having trouble figuring out how to include the meta in the query.

enter image description here

Here is what I am trying to do to test one of the fields, but results are still negative.

add_action( 'pre_get_terms', [$this, 'filter_feedback_stats_admin_columns'] );
public function filter_feedback_stats_admin_columns( $query ) {
    // Get the page
    global $pagenow;
    
    // Only if current post taxonomy or edit page in admin
    $taxonomy = isset($_GET['taxonomy']) ? $_GET['taxonomy'] : '';
    if ( !is_admin() || $pagenow !== 'edit-tags.php' || $taxonomy != 'feedback-stats' && !isset($_GET['s'])) {
        return $query; 
    }

    // Search keyword
    $s = $_GET['s'];
    
    // // store current query vars
    $query_vars = $query->query_vars;
    $args = [];
    
    // set meta query
    $args['meta_query'] = [
        [
        'key'       => 'access_id',
        'value'     => $s,
        'compare'   => 'LIKE'
        ]
    ];
    
    // Add it
    $query->query_vars = array_merge( $query_vars, $args );
}

1 Answer 1

1

Most likely because the query is also searching for a match against the term name/slug, as opposed to "match either term name or meta field".

If you don't need the search to also look for matches by term name/slug, just unset the search term early on when you apply your meta query:

add_action( 'parse_term_query', function ( $wp_term_query ) {
    $taxonomy = $wp_term_query->query_vars['taxonomy'];

    $search = $wp_term_query->query_vars['search'] ?? '';

    if ( ! $search || $taxonomy !== [ 'feedback-stats' ] ) {
        return;
    }

    unset( $wp_term_query->query_vars['search'] );

    $meta_query = [
        'relation' => 'OR',
    ];

    $search_meta_keys = [
        'access_id',
        // Add your other meta keys
    ];

    foreach ( $search_meta_keys as $key ) {
        $meta_query[] = [
            'key' => $key,
            'value' => $search,
            'compare' => 'LIKE',
        ];
    }

    $wp_term_query->query_vars['meta_query'] = $meta_query;
});

If you do indeed need the search to match either the term name or field(s), there's a bit more work ahead of you as we'll need to hook into the generated SQL of the meta query and create an OR search.

1
  • This is exactly what I needed @TheDeadMedic, and it works perfectly! I don't need to search name or slug. Thanks for the help!
    – Michael
    May 24 at 17:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.