Skip to:
Content
Pages
Categories
Search
Top
Bottom

[Resolved] Order Members Loop by Custom Field Value

  • @duablellc

    Participant

    I was asked recently about how to order members in a loop based on the value of a (numerical) custom field in their profile.

    Place the following in your functions.php file:

    <?php
    function du_users_by_value($field_id){
    /* duable.com */
    $numberedUsers = array();
    $orderedIds = array();

    if ( bp_has_members(bp_ajax_querystring( ‘members’ ) ) ) :
    while ( bp_members() ) : bp_the_member();
    /* Get the field value from all members */
    $number_field = xprofile_get_field_data($field_id, bp_get_member_user_id());
    /* Push user id and number value to an array */
    $numberedUsers[$number_field] = bp_get_member_user_id();
    endwhile;
    endif;

    /* Sort the members by the custom field value, highest to lowest */
    ksort($numberedUsers);

    /* Create a new array with just the member id’s in the correct order */
    foreach ($numberedUsers as $user) {
    array_push($orderedIds, $user)
    }

    /* Echo out the include argument along with comma seperated values of the members in order */
    $orderedIds=implode(“,”,$orderedIds);
    echo ‘include=’ . $orderedIds;
    }
    ?>

    Place the following in your template file where you want the loop to show up:

    <?php
    /* Your Loop: Replace field_id with the id or name of the field to order by */
    if ( bp_has_members( du_users_by_value(‘field_id’) . ‘&’ . bp_ajax_querystring( ‘members’ ) ) ) :
    while ( bp_members() ) : bp_the_member();
    DO SOMETHING HERE
    endwhile;
    endif;
    ?>

    Feel free to post any questions or bugs.

Viewing 4 replies - 1 through 4 (of 4 total)
  • @martyn_

    Participant

    Does the include override $type? that isn’t obvious…

    @duablellc

    Participant

    Do you mean does it override another argument being passed to bp_has_members()?

    It actually might, in which case you will have to add another set of conditionals to the line commented /* Push user id and number value to an array */. With this method, you’d have to generate your loop parameters through the custom function.

    @martyn_

    Participant

    At face value, the inlude= argument says which members should be output, not the order. The documentation is a little weak here, but a quick test suggested that I was still getting the sort order of ‘last active’ when I tried.

    I may have goofed somewhere….

    @buddhatunes

    Participant

    Any suggestions on how to do with an existing drop-down select box field type in Profile Fields?

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘[Resolved] Order Members Loop by Custom Field Value’ is closed to new replies.
Skip to toolbar