BP_Groups_Group::get( array $args = array() )

Query for groups.


Description Description

See also See also


Top ↑

Parameters Parameters

$args

(Optional) Array of parameters. All items are optional.

  • 'type'
    (string) Optional. Shorthand for certain orderby/order combinations. 'newest', 'active', 'popular', 'alphabetical', 'random'. When present, will override orderby and order params. Default: null.
  • 'orderby'
    (string) Optional. Property to sort by. 'date_created', 'last_activity', 'total_member_count', 'name', 'random', 'meta_id'. Default: 'date_created'.
  • 'order'
    (string) Optional. Sort order. 'ASC' or 'DESC'. Default: 'DESC'.
  • 'per_page'
    (int) Optional. Number of items to return per page of results. Default: null (no limit).
  • 'page'
    (int) Optional. Page offset of results to return. Default: null (no limit).
  • 'user_id'
    (int) Optional. If provided, results will be limited to groups of which the specified user is a member. Default: null.
  • 'slug'
    (array|string) Optional. Array or comma-separated list of group slugs to limit results to. Default: false.
  • 'search_terms'
    (string) Optional. If provided, only groups whose names or descriptions match the search terms will be returned. Allows specifying the wildcard position using a '*' character before or after the string or both. Works in concert with $search_columns. Default: false.
  • 'search_columns'
    (string) Optional. If provided, only apply the search terms to the specified columns. Works in concert with $search_terms. Default: empty array.
  • 'group_type'
    (array|string) Array or comma-separated list of group types to limit results to.
  • 'group_type__in'
    (array|string) Array or comma-separated list of group types to limit results to.
  • 'group_type__not_in'
    (array|string) Array or comma-separated list of group types that will be excluded from results.
  • 'meta_query'
    (array) Optional. An array of meta_query conditions. See WP_Meta_Query::queries for description.
  • 'value'
    (array|string) Optional. Array or comma-separated list of group IDs. Results will be limited to groups within the list. Default: false.
  • 'parent_id'
    (array|string) Optional. Array or comma-separated list of group IDs. Results will be limited to children of the specified groups. Default: null.
  • 'exclude'
    (array|string) Optional. Array or comma-separated list of group IDs. Results will exclude the listed groups. Default: false.
  • 'update_meta_cache'
    (bool) Whether to pre-fetch groupmeta for the returned groups. Default: true.
  • 'update_admin_cache'
    (bool) Whether to pre-fetch administrator IDs for the returned groups. Default: false.
  • 'show_hidden'
    (bool) Whether to include hidden groups in results. Default: false.
  • 'status'
    (array|string) Optional. Array or comma-separated list of group statuses to limit results to. If specified, $show_hidden is ignored. Default: empty array.
  • 'fields'
    (string) Which fields to return. Specify 'ids' to fetch a list of IDs. Default: 'all' (return BP_Groups_Group objects). If set, meta and admin caches will not be prefetched.

Default value: array()


Top ↑

Return Return

(array)

  • 'groups'
    (array) Array of group objects returned by the paginated query. (IDs only if fields is set to ids.)
  • 'total'
    (int) Total count of all groups matching non- paginated query params.


Top ↑

Source Source

File: bp-groups/classes/class-bp-groups-group.php

	public static function get( $args = array() ) {
		global $wpdb;

		$function_args = func_get_args();

		// Backward compatibility with old method of passing arguments.
		if ( ! is_array( $args ) || count( $function_args ) > 1 ) {
			_deprecated_argument( __METHOD__, '1.7', sprintf( __( 'Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddypress' ), __METHOD__, __FILE__ ) );

			$old_args_keys = array(
				0 => 'type',
				1 => 'per_page',
				2 => 'page',
				3 => 'user_id',
				4 => 'search_terms',
				5 => 'include',
				6 => 'populate_extras',
				7 => 'exclude',
				8 => 'show_hidden',
			);

			$args = bp_core_parse_args_array( $old_args_keys, $function_args );
		}

		$defaults = array(
			'type'               => null,
			'orderby'            => 'date_created',
			'order'              => 'DESC',
			'per_page'           => null,
			'page'               => null,
			'user_id'            => 0,
			'slug'               => array(),
			'search_terms'       => false,
			'search_columns'     => array(),
			'group_type'         => '',
			'group_type__in'     => '',
			'group_type__not_in' => '',
			'meta_query'         => false,
			'include'            => false,
			'parent_id'          => null,
			'update_meta_cache'  => true,
			'update_admin_cache' => false,
			'exclude'            => false,
			'show_hidden'        => false,
			'status'             => array(),
			'fields'             => 'all',
		);

		$r = bp_parse_args( $args, $defaults, 'bp_groups_group_get' );

		$bp = buddypress();

		$sql = array(
			'select'     => "SELECT DISTINCT g.id",
			'from'       => "{$bp->groups->table_name} g",
			'where'      => '',
			'orderby'    => '',
			'pagination' => '',
		);

		if ( ! empty( $r['user_id'] ) ) {
			$sql['from'] .= " JOIN {$bp->groups->table_name_members} m ON ( g.id = m.group_id )";
		}

		$where_conditions = array();

		if ( ! empty( $r['status'] ) ) {
			if ( ! is_array( $r['status'] ) ) {
				$r['status'] = preg_split( '/[\s,]+/', $r['status'] );
			}
			$r['status'] = array_map( 'sanitize_title', $r['status'] );
			$status_in = "'" . implode( "','", $r['status'] ) . "'";
			$where_conditions['status'] = "g.status IN ({$status_in})";
		} elseif ( empty( $r['show_hidden'] ) ) {
			$where_conditions['hidden'] = "g.status != 'hidden'";
		}

		if ( ! empty( $r['slug'] ) ) {
			if ( ! is_array( $r['slug'] ) ) {
				$r['slug'] = preg_split( '/[\s,]+/', $r['slug'] );
			}
			$r['slug'] = array_map( 'sanitize_title', $r['slug'] );
			$slug_in = "'" . implode( "','", $r['slug'] ) . "'";
			$where_conditions['slug'] = "g.slug IN ({$slug_in})";
		}

		$search = '';
		if ( isset( $r['search_terms'] ) ) {
			$search = trim( $r['search_terms'] );
		}

		if ( $search ) {
			$leading_wild = ( ltrim( $search, '*' ) != $search );
			$trailing_wild = ( rtrim( $search, '*' ) != $search );
			if ( $leading_wild && $trailing_wild ) {
				$wild = 'both';
			} elseif ( $leading_wild ) {
				$wild = 'leading';
			} elseif ( $trailing_wild ) {
				$wild = 'trailing';
			} else {
				// Default is to wrap in wildcard characters.
				$wild = 'both';
			}
			$search = trim( $search, '*' );

			$searches = array();
			$leading_wild = ( 'leading' == $wild || 'both' == $wild ) ? '%' : '';
			$trailing_wild = ( 'trailing' == $wild || 'both' == $wild ) ? '%' : '';
			$wildcarded = $leading_wild . bp_esc_like( $search ) . $trailing_wild;

			$search_columns = array( 'name', 'description' );
			if ( $r['search_columns'] ) {
				$search_columns = array_intersect( $r['search_columns'], $search_columns );
			}

			foreach ( $search_columns as $search_column ) {
				$searches[] = $wpdb->prepare( "$search_column LIKE %s", $wildcarded );
			}

			$where_conditions['search'] = '(' . implode(' OR ', $searches) . ')';
		}

		$meta_query_sql = self::get_meta_query_sql( $r['meta_query'] );

		if ( ! empty( $meta_query_sql['join'] ) ) {
			$sql['from'] .= $meta_query_sql['join'];
		}

		if ( ! empty( $meta_query_sql['where'] ) ) {
			$where_conditions['meta'] = $meta_query_sql['where'];
		}

		// Only use 'group_type__in', if 'group_type' is not set.
		if ( empty( $r['group_type'] ) && ! empty( $r['group_type__in']) ) {
			$r['group_type'] = $r['group_type__in'];
		}

		// Group types to exclude. This has priority over inclusions.
		if ( ! empty( $r['group_type__not_in'] ) ) {
			$group_type_clause = self::get_sql_clause_for_group_types( $r['group_type__not_in'], 'NOT IN' );

		// Group types to include.
		} elseif ( ! empty( $r['group_type'] ) ) {
			$group_type_clause = self::get_sql_clause_for_group_types( $r['group_type'], 'IN' );
		}

		if ( ! empty( $group_type_clause ) ) {
			$where_conditions['group_type'] = $group_type_clause;
		}

		if ( ! empty( $r['user_id'] ) ) {
			$where_conditions['user'] = $wpdb->prepare( "m.user_id = %d AND m.is_confirmed = 1 AND m.is_banned = 0", $r['user_id'] );
		}

		if ( ! empty( $r['include'] ) ) {
			$include        = implode( ',', wp_parse_id_list( $r['include'] ) );
			$where_conditions['include'] = "g.id IN ({$include})";
		}

		if ( ! is_null( $r['parent_id'] ) ) {
			// For legacy reasons, `false` means groups with no parent.
			if ( false === $r['parent_id'] ) {
				$parent_id = 0;
			} else {
				$parent_id = implode( ',', wp_parse_id_list( $r['parent_id'] ) );
			}

			$where_conditions['parent_id'] = "g.parent_id IN ({$parent_id})";
		}

		if ( ! empty( $r['exclude'] ) ) {
			$exclude        = implode( ',', wp_parse_id_list( $r['exclude'] ) );
			$where_conditions['exclude'] = "g.id NOT IN ({$exclude})";
		}

		/* Order/orderby ********************************************/

		$order   = $r['order'];
		$orderby = $r['orderby'];

		// If a 'type' parameter was passed, parse it and overwrite
		// 'order' and 'orderby' params passed to the function.
		if (  ! empty( $r['type'] ) ) {

			/**
			 * Filters the 'type' parameter used to overwrite 'order' and 'orderby' values.
			 *
			 * @since 2.1.0
			 *
			 * @param array  $value Converted 'type' value for order and orderby.
			 * @param string $value Parsed 'type' value for the get method.
			 */
			$order_orderby = apply_filters( 'bp_groups_get_orderby', self::convert_type_to_order_orderby( $r['type'] ), $r['type'] );

			// If an invalid type is passed, $order_orderby will be
			// an array with empty values. In this case, we stick
			// with the default values of $order and $orderby.
			if ( ! empty( $order_orderby['order'] ) ) {
				$order = $order_orderby['order'];
			}

			if ( ! empty( $order_orderby['orderby'] ) ) {
				$orderby = $order_orderby['orderby'];
			}
		}

		// 'total_member_count' and 'last_activity' sorts require additional table joins.
		if ( 'total_member_count' === $orderby ) {
			$sql['from'] .= " JOIN {$bp->groups->table_name_groupmeta} gm_total_member_count ON ( g.id = gm_total_member_count.group_id )";
			$where_conditions['total_member_count'] = "gm_total_member_count.meta_key = 'total_member_count'";
		} elseif ( 'last_activity' === $orderby ) {

			$sql['from'] .= " JOIN {$bp->groups->table_name_groupmeta} gm_last_activity on ( g.id = gm_last_activity.group_id )";
			$where_conditions['last_activity'] = "gm_last_activity.meta_key = 'last_activity'";
		}

		// If 'meta_id' is the requested order, and there's no meta query, fall back to the default.
		if ( 'meta_id' === $orderby && empty( $meta_query_sql['join'] ) ) {
			$orderby = 'date_created';
		}

		// Sanitize 'order'.
		$order = bp_esc_sql_order( $order );

		/**
		 * Filters the converted 'orderby' term.
		 *
		 * @since 2.1.0
		 *
		 * @param string $value   Converted 'orderby' term.
		 * @param string $orderby Original orderby value.
		 * @param string $value   Parsed 'type' value for the get method.
		 */
		$orderby = apply_filters( 'bp_groups_get_orderby_converted_by_term', self::convert_orderby_to_order_by_term( $orderby ), $orderby, $r['type'] );

		// Random order is a special case.
		if ( 'rand()' === $orderby ) {
			$sql['orderby'] = "ORDER BY rand()";
		} else {
			$sql['orderby'] = "ORDER BY {$orderby} {$order}";
		}

		if ( ! empty( $r['per_page'] ) && ! empty( $r['page'] ) && $r['per_page'] != -1 ) {
			$sql['pagination'] = $wpdb->prepare( "LIMIT %d, %d", intval( ( $r['page'] - 1 ) * $r['per_page']), intval( $r['per_page'] ) );
		}

		$where = '';
		if ( ! empty( $where_conditions ) ) {
			$sql['where'] = implode( ' AND ', $where_conditions );
			$where = "WHERE {$sql['where']}";
		}

		$paged_groups_sql = "{$sql['select']} FROM {$sql['from']} {$where} {$sql['orderby']} {$sql['pagination']}";

		/**
		 * Filters the pagination SQL statement.
		 *
		 * @since 1.5.0
		 *
		 * @param string $value Concatenated SQL statement.
		 * @param array  $sql   Array of SQL parts before concatenation.
		 * @param array  $r     Array of parsed arguments for the get method.
		 */
		$paged_groups_sql = apply_filters( 'bp_groups_get_paged_groups_sql', $paged_groups_sql, $sql, $r );

		$cached = bp_core_get_incremented_cache( $paged_groups_sql, 'bp_groups' );
		if ( false === $cached ) {
			$paged_group_ids = $wpdb->get_col( $paged_groups_sql );
			bp_core_set_incremented_cache( $paged_groups_sql, 'bp_groups', $paged_group_ids );
		} else {
			$paged_group_ids = $cached;
		}

		if ( 'ids' === $r['fields'] ) {
			// We only want the IDs.
			$paged_groups = array_map( 'intval', $paged_group_ids );
		} else {
			$uncached_group_ids = bp_get_non_cached_ids( $paged_group_ids, 'bp_groups' );
			if ( $uncached_group_ids ) {
				$group_ids_sql = implode( ',', array_map( 'intval', $uncached_group_ids ) );
				$group_data_objects = $wpdb->get_results( "SELECT g.* FROM {$bp->groups->table_name} g WHERE g.id IN ({$group_ids_sql})" );
				foreach ( $group_data_objects as $group_data_object ) {
					wp_cache_set( $group_data_object->id, $group_data_object, 'bp_groups' );
				}
			}

			$paged_groups = array();
			foreach ( $paged_group_ids as $paged_group_id ) {
				$paged_groups[] = new BP_Groups_Group( $paged_group_id );
			}

			$group_ids = array();
			foreach ( (array) $paged_groups as $group ) {
				$group_ids[] = $group->id;
			}

			// Grab all groupmeta.
			if ( ! empty( $r['update_meta_cache'] ) ) {
				bp_groups_update_meta_cache( $group_ids );
			}

			// Prefetch all administrator IDs, if requested.
			if ( $r['update_admin_cache'] ) {
				BP_Groups_Member::prime_group_admins_mods_cache( $group_ids );
			}

			// Set up integer properties needing casting.
			$int_props = array(
				'id', 'creator_id', 'enable_forum'
			);

			// Integer casting.
			foreach ( $paged_groups as $key => $g ) {
				foreach ( $int_props as $int_prop ) {
					$paged_groups[ $key ]->{$int_prop} = (int) $paged_groups[ $key ]->{$int_prop};
				}
			}

		}

		// Find the total number of groups in the results set.
		$total_groups_sql = "SELECT COUNT(DISTINCT g.id) FROM {$sql['from']} $where";

		/**
		 * Filters the SQL used to retrieve total group results.
		 *
		 * @since 1.5.0
		 *
		 * @param string $t_sql     Concatenated SQL statement used for retrieving total group results.
		 * @param array  $total_sql Array of SQL parts for the query.
		 * @param array  $r         Array of parsed arguments for the get method.
		 */
		$total_groups_sql = apply_filters( 'bp_groups_get_total_groups_sql', $total_groups_sql, $sql, $r );

		$cached = bp_core_get_incremented_cache( $total_groups_sql, 'bp_groups' );
		if ( false === $cached ) {
			$total_groups = (int) $wpdb->get_var( $total_groups_sql );
			bp_core_set_incremented_cache( $total_groups_sql, 'bp_groups', $total_groups );
		} else {
			$total_groups = (int) $cached;
		}

		return array( 'groups' => $paged_groups, 'total' => $total_groups );
	}

Top ↑

Changelog Changelog

Changelog
Version Description
2.9.0 Added $slug parameter.
2.8.0 Changed $search_terms parameter handling and added $search_columns parameter.
2.7.0 Added $update_admin_cache and $parent_id parameters.
2.6.0 Added $group_type, $group_type__in, and $group_type__not_in parameters.
1.6.0 Introduced.

Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.