Problem: I have a View that I would like to filter by post author. That View may be displayed in a BuddyPress profile. I have a PHP function provided by BB that will help determine the User ID based on the profile being displayed.
Solution: Use the Views Filter API wpv_filter_query to programmatically set a post author filter in this View using the function provided by BuddyPress / BuddyBoss.
// Override the post author filter of a View shown in the BP User page to display only that User's posts.
// https://toolset.com/forums/topic/filtering-views-query-by-author-for-a-profile-page/
add_filter( 'wpv_filter_query', 'tssupp_bp_force_author_filter',99,3 );
function tssupp_bp_force_author_filter( $query_args,$views_settings, $view_id) {
$views = array( 123, 456 );
if ( in_array( $view_id, $views ) ){
// post author equals bp_displayed_user_id() if function exists
$query_args['author'] = function_exists('bp_displayed_user_id') ? bp_displayed_user_id() : 0;
}
return $query_args;
}
You would replace 123, 456 with a comma-separated list of View IDs which you would like to filter by post author. This post author filter will only work if the function provided by BP/BB returns the correct User ID. If you try to place this View on a page where the BP/BB function does not return the correct value, the View will not be filtered appropriately.