1

I'm trying to filter so that only the creators of the respective categories can edit them. I created a cat_author meta field and associated it to the taxonomy. In this way, every taxonomy has an author. And I tended to filter with

add_filter( 'pre_get_terms', 'filter_cat_by_u_id', 99, 1 );
function filter_cat_by_u_id( $query ) {
    if ( ! is_admin() ) {
      return $query;
    }
    global $pagenow;    
    if ( 'edit-tags.php' === $pagenow ) {
        $meta_query = array(
            array(
                'key' => 'cat_author',
                'value' => get_current_user_id(),
                'compare' => '='
            )
        );
        $query->set( 'meta_query', $meta_query );
    }
    return $query;
}

But I'm not getting a good result. Does anyone have any tips?

UPDATE:

add_filter( 'get_terms_args', 'filter_cat_by_u_id' );
function filter_cat_by_u_id( $args ) {
    global $pagenow;

    if ( is_admin() && 'edit-tags.php' === $pagenow ) {
        $args['meta_query'] = array( 
            array(
                'key' => 'cat_author',
                'value' => get_current_user_id(),
                'compare' => '='
            )
        );
    }

    return $args;
}

Thanks to Sally I this solution works perfectly fine to filter the list of custom categories in wp-admin/dahsboar.

1 Answer 1

1

The WP_Term_Query class doesn't have a method named set, and calling $query->set() in my case resulted in a fatal/critical error saying "Call to undefined method WP_Term_Query::set()". :/

But you can directly modify the query_vars property (i.e. $query->query_vars), like so, to set, unset or override any query variables like meta_query:

// Use this:
$query->query_vars['meta_query'] = $meta_query;

// NOT this (which causes a fatal error):
$query->set( 'meta_query', $meta_query );

Or you could instead use the get_terms_args hook:

add_filter( 'get_terms_args', 'filter_cat_by_u_id' );
function filter_cat_by_u_id( $args ) {
    global $pagenow;

    if ( is_admin() && 'edit-tags.php' === $pagenow ) {
        $args['meta_query'] = array( your code here );
    }

    return $args;
}
1
  • 1
    Ty so much Sally. You save me! May 25 at 0:02

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.