0

I am trying to filter posts based on a custom field I have set up for a user. allowed_categories is a multiselect custom field on the add new/edit user page that lets the admin choose which terms in a taxonomy the user has access to. In this case the taxonomy is product_cat. I added a user and chose some terms, that is working fine. I wrote a function that should get the product categories the user is assigned to and filters returned results based on those values. Problem is it is not working? Probably overlooking something simple here..

What is returned when I print the allowed_categories from the current user.

Array
(
    [0] => 100
)

My pre_get_posts action

add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );

function custom_pre_get_posts_query( $q ) {

    if ( ! $q->is_main_query() ) return;
    if ( ! $q->is_post_type_archive() ) return;

    if ( ! is_admin() && is_shop() ) {

        $user = wp_get_current_user();

        $allowedCats = get_field('allowed_categories', 'user_' . $user->ID);

        if( isset($cats) && $cats > 0) {
            $q->set( 'tax_query', array(array(
                'taxonomy' => 'product_cat',
                'field' => 'id',
                'terms' => $allowedCats,
                'operator' => 'NOT IN'
            )));
        }

    }

    remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );

}
0

You need to modify the tax_query block of code like below-

$q->set( 'tax_query', array(array(
    'taxonomy' => 'product_cat',
    'field' => 'term_id', // Here it would be 'term_id' instead of only 'ID'.
    'terms' => $allowedCats,
    'operator' => 'IN' // May be it would be 'IN' in stead of 'NOT IN'. Cause you are passing allowed product categories.
)));

Hope that helps.

|improve this answer|||||

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.