0

I have lots of authors each with a post each. I only want posts that have a specific term (from a custom taxonomy) to be visible by other authors with the same term in their post. In other words, if the post author doesn't have the specific term in their own post then they can't see any other posts with that term. I hope that makes sense?

1

You'd do something like

$current_user = wp_get_current_user();

to get the current user, then you'd want their posts

$current_user_posts = get_posts(array(
  'author' =>  $current_user->ID,
  'posts_per_page' => -1
);

with their posts, you'd cycle through them, and grab the terms

$current_user_terms = array();
foreach ($current_user_posts as $user_post) {
    $user_terms = wp_get_post_terms($user_post->ID, 'custom_tax', array("fields" => "ids"));
    foreach ($user_terms as $user_term ) {
        if (!in_array($user_term->term_id, $current_user_terms))
            $current_user_terms[] = $user_term->term_id;
    }
}

Then you'd change what you show to the current user by modifying your query to show only the selected terms:

$your_query = new WP_Query( array(
    'tax_query' => array(
        array(
            'taxonomy' => 'custom_tax',
            'field'    => 'term_id',
            'terms'    => $current_user_terms,
        )
     )
));
if ( $the_query->have_posts() ) { ..

However it sounds like you're wanting this is working off of Wordpress main queries, not custom queries. You'd have to look into pre_get_posts or other ways to modify they main query before it's fired.

You will also have to decided if you want this to run in admin as well as the front end, pre_get_posts does work on both front and backend, so is_admin() comes in handy in that hook.

also, as you can imagine that's a lot of queries to be running each page load, so you'd probably want to wrap it all in a function, and then call to it with a cache system like Transients_API.

You would also likely have to tap into post_save to update/cache-break the transient so if new terms are made, they instantly get the new viewing

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.