Populated Advanced Custom Fields (ACF) Select With BuddyPress Groups


About The Author
Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.







Populated Advanced Custom Fields (ACF) Select With BuddyPress Groups

As I’ve mentioned, I’ve recently taken on a project that works heavily with BuddyPress. While I have a little bit of past experience with BuddyPress, it’s a bit of a learning game. Of course I’m leveraging one of my favorite plugins, Advanced Custom Fields whenever possible. Today, we’re going to look at a function I wrote to populate an ACF select fields based on BuddyPress groups the user is apart of. Here is the snippet in its entirety:

function acf_load_bp_groups( $field ) {
  // Reset choices
  $field['choices'] = array();
  $user_id = get_current_user_id();
  $groups = array();
  if ( bp_has_groups('user_id=' . $user_id) ) :
	while ( bp_groups() ) : bp_the_group(); 
	$groups[] = bp_get_group_name() . '_' . bp_get_group_id();
	endwhile; 
  endif;
 
  // Populate choices
  foreach( $groups as $group ) {
	  $groupvalues = explode('_', $group);
    $field['choices'][ $groupvalues[1] ] = $groupvalues[0];
  }
 
  // Return choices
  return $field;
 
}
// Populate select field using filter
add_filter('acf/load_field/name=your_field_name', 'acf_load_bp_groups');

Additional parameters could be placed within the BuddyPress query groups line if needed. Hope this helps somebody else in need!


Share Your Thoughts

Leave a Reply

Your email address will not be published.


Related Stuff You Might Like







WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!