0

I created custom taxonomy named 'Customers'. In admin panel, different users will login and create their Customers in that taxonomy. I want to show them their own Customers only. Currently they can see all Customers. See this screenshot- enter image description here

1 Answer 1

0

I don't have enough time to test the full code, but you can get the idea from my code.

Taxonomies themselves don't have a direct association with authors. So there is no easy way to do it.

You can add custom meta fields to custom taxonomies also. So you can store the current user ID in a custom meta field.

function save_current_user_id_for_customers($term_id, $tt_id, $taxonomy) {
   
    if ($taxonomy == 'customers') {
        
        $current_user_id = get_current_user_id();

        
        update_term_meta($term_id, 'user_id', $current_user_id);
    }
}

add_action('create_term', 'save_current_user_id_for_customers', 10, 3);

Then you can use a parse_tax_query filter to filter customers.

function filter_customers_taxonomy_query($query) {
    global $pagenow;

    
    if ($pagenow == 'edit-tags.php' && isset($_GET['taxonomy']) && $_GET['taxonomy'] == 'customers') {
        
        $current_user_id = get_current_user_id();

        
        $tax_query = array(
            array(
                'taxonomy' => 'customers',
                'field'    => 'user_id', // Change this to the actual custom field name
                'terms'    => $current_user_id,
                'operator' => 'IN',
            ),
        );

        $query->tax_query->queries = $tax_query;
        $query->tax_query->relation = 'AND';
    }
}

add_action('parse_tax_query', 'filter_customers_taxonomy_query');
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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