Skip to:
Content
Pages
Categories
Search
Top
Bottom

Custom groups loop with groups meta

  • @prowseed

    Participant

    Hello,
    I would like to ask how can I manage the following situation:
    Let’s say I allow users to input custom string while they create a group. This may be a country. So it is saved to groupmeta database as [ group-country : Russia ]. Then I would like to make a custom groups loop on a specific page where I display only groups that have group-country == Russia since users wouldn’t like to see groups from other countries as they don’t interest them.

    I was searching through internet for solution and managed to accomplish my task with this:
    • in functions.php

    `function include_groups_by_meta($theMetaValue, $theMetaField) {
    $groupArray = array();
    if (bp_has_groups()) :
    while (bp_groups()) : bp_the_group();
    $theFieldValue = groups_get_groupmeta( bp_get_group_id(), $theMetaField );
    if ($theFieldValue==$theMetaValue) {
    array_push($groupArray,bp_get_group_id());
    }
    endwhile;
    endif;

    $theIncludeString=implode(“,”,$groupArray);
    return $theIncludeString;
    }`

    • and in my loop

    `$args = array(
    ‘type’ => ‘random’,
    ‘max’ => 3,
    ‘include’ => include_groups_by_meta(‘Russia’, ‘group-country’)
    );
    if ( bp_has_groups ( $args ) ): ?>`

    However, first of all, what I really do are two loops which could be overloading, and secondly when there is no group in particular country my loop loops through all of the possible groups. Is there some cleaner way to accomplish my task?

    Thanks in advance.

Viewing 3 replies - 1 through 3 (of 3 total)
  • @shanebp

    Moderator

    Maybe something like this – untested:
    `
    $group_ids = $wpdb->get_var(“SELECT id FROM groups_groupmets WHERE meta_key = ‘group-country’ AND meta_value = ‘Russia'”);

    foreach ( $group_ids as $group_id ) {
    $group_ids_str[] = $group_id->id”;
    }
    $theIncludeString = implode (‘,’, $group_ids_str);

    if( !empty($theIncludeString) ) // build args and start loop
    else … ?
    `

    @anonymized-96400

    Inactive

    Rather than doing two loops, one of which will run through all available groups to perform a database request each time, just do 1 query that gets all group ids and then pass those ids to the include parameter. Something like this:

    `function my_get_groups_for_country( $country = ” ) {
    global $wpdb, $bp;

    $group_ids = $wpdb->get_col( $wpdb->prepare( “
    SELECT group_id
    FROM {$bp->groups->table_name_groupmeta}
    WHERE meta_key = ‘group-country’
    AND meta_value = %s
    “, $country ) );

    return $group_ids:
    }`

    @prowseed

    Participant

    Thanks shanebp for your effort, but Boris’ idea seems to be more sensible for me. Thanks you both for answer.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Custom groups loop with groups meta’ is closed to new replies.
Skip to toolbar