• Hello, how can i modify the main query so it would return posts as usual, but also include private posts related to specific category from which the user has permission to read private posts. In other words there are posts, some of them are private, and each one of them is related to a category, an authorized user somehow should be able to receive in the main query thouse private posts (alongside with non private posts) but only if they subscribed to this category.

    Say I have a user with the role “Subscriber” and the custom capability “read_private_posts_from_categoty_economics”, which I add using this code, and i’m using ACF here:

    add_action('profile_update', 'set_capabilities', 10, 3);
    
    function set_capabilities($user_id, $oldUserData, $newUserData)
    {
        $user = new WP_User($user_id);
    
        $categories = get_field('can_read_categories', 'user_' . $user_id);
    
        if ($categories) {
            foreach ($categories as $category) {
                $user->add_cap('read_private_posts_from_categoty_' . $category->slug);
            }
        }
    }

    what would be the right way (WP way) to achieve this functionality, and if this even possible to do with what WP provides?

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    You can modify the query via the “pre_get_posts” action. Add “private” to the array assigned to “post_status” query var.

    Before doing so, confirm the current user has the appropriate capability to view private posts which are to be part of this query. You can use current_user_can() to verify capability. You likely also need to confirm the query includes query vars for the appropriate category term. For example if ('economics'== $query->get_query_var('category_name')):. There are numerous ways a category term could be specified. You’ll need to check the query var actually used in your specific situation.

Viewing 1 replies (of 1 total)
  • The topic ‘Include private posts from specific categories to the main query’ is closed to new replies.