BuddyPress 修復工具管理屏幕

BuddyPress 修復工具管理屏幕

Codex Home → Administrator Guide → BuddyPress Repair Tools Admin Screen
BuddyPress Repair Tools Admin Screen

Occasionally, BP friend counts and other data can get out of sync. The new Tools screen lets admins manually reset these values. Go to wp-admin Menu > Tools > BuddyPress and run repair tools one at a time only, especially on large sites.
When you have a new installation, the default repair tools are for:

Count total members
Repair user 「last activity」 data

As more people register, and when you enable the Friends and Groups components, you』ll find repair tools for the additional data generated per image below:

Count friends for each user
Count groups for each user
Count total members
Repair user 「last activity」 data

使用帶有 BuddyPress 的 S2member 時的有用功能和技巧

使用帶有 BuddyPress 的 S2member 時的有用功能和技巧

Codex Home → Developer Resources → User Submitted Guides → Useful Functions and Hacks When Using S2member w/ BuddyPress
Useful Functions and Hacks When Using S2member w/ BuddyPress

Hey there guys, i』m working on a website where i』m integrating s2member functionality with buddypress. I thought some of the things I』ve come across may be useful to other people.
1. Filter Users Displayed in Members Directory by s2member role.
In your plugins/buddypress/bp-templates/bp-legacy/buddypress/members/ folder edit the file 「members-loop.php」. Just under
at the top 20 lines of the file we need to write some PHP code to build a comma separated list of ID』s based on the s2member role or roles that we want. In my case I wanted only members of 「s2member_level2″.
It is recommended to only ever edit a copy of template file that you have copied over to your theme or child theme otherwise your changes will be overwritten on updates.
$args = array('role' => 's2member_level2', 'fields' => array('id'));
// The User Query
$user_query = new WP_User_Query( $args );
$custom_ids = '';
for($i = 0;$i results); $i++){
$a = $user_query->results[$i]->id;
$custom_ids .= $a.",";
}

Now that we』ve made a comma separated string of ids ($custom_ids), we need to pass it to the members loop.
Change
if(bp_has_members( bp_ajax_querystring( 'members' ) ) ) :
to
if(bp_has_members('per_page=30&type=alphabetical&'.'include='.$custom_ids ) ) :
In my case I wanted to make sure at most 30 members showed up, and that they were in alphabetical order.
Done.
2. Importing s2member custom fields to buddypress fields
You may be asking; why??? Well, it turns out that when you have the s2member option to integrate with buddypress it doesn』t actually import it』d data to the buddypress tables. It just binds it』s self to the 『Base』 group, Which will show up by default in buddypress profiles. When it doesn』t import to the buddypress tables, it was very difficult for me to manipulate how the information showed up. Particularly the fact that I have the users give me their address information, and I don』t want that to even be an option to show in user profiles.
So instead of using s2member to integrate automatically, I wrote a function that would check a users information when they login. If they have certain information in s2member that is not in their BP Profile, it will add it automatically.
Option 1:
in functions.php add the code:
<?php

add_action('wp_head','s2_profile_field_update',10,2);
function s2_profile_field_update() {
global $current_user;
get_currentuserinfo();
if(current_user_is("s2member_level2")){
if(get_user_field("s2member_login_counter") id) == '' && get_user_field('nationality') != '') {
xprofile_set_field_data('Nationality', $current_user->id, get_user_field('nationality'));
}

if(xprofile_get_field_data('Age', $current_user->id) == '' && get_user_field('age') != '') {
xprofile_set_field_data('Age', $current_user->id, get_user_field('age'));
}

if(xprofile_get_field_data('School', $current_user->id) == '' && get_user_field('school') != '') {
xprofile_set_field_data('School', $current_user->id, get_user_field('school'));
}
}
}
}

?>
You can change Nationality to what ever the name is of the extended BP field (in users>profile fields).
And of course you can duplicate the if statements for how every many fields you want to import from s2memeber -> BP.
Also note that if(get_user_field("s2member_login_counter") < 1000) mean』s that this process will run for any user that logs in with membership role s2member_level2 and has logged in less than 1000 times. I used 1000 times because I want any member at this moment who logs in to have their profiles populated. In the future I will drop it down to 1 or 2.
Alternatively we could use a for loop in order to make any later changes a bit simpler:
// Function to populate BP Profile Fields w/ S2member Fields.
add_action('wp_head','s2_profile_field_update',10,2);
function s2_profile_field_update() {
global $current_user;

//Array of xprofile field names
$xprofile_fields = array('Nationality','Age','School');

//Array of s2member field slugs
$s2member_fields = array('nationality','age','school');

get_currentuserinfo();
if( current_user_is("s2member_level2") ) {
if(get_user_field("s2member_login_counter") < 1000)
{
for($i = 0; $i id) == '' && get_user_field($s2member_fields[i]) != '' )
{
xprofile_set_field_data($xprofile_fields[i], $current_user->id, get_user_field($s2member_fields[i]) );
}
}
}
}
}

Option 2: Suggested by @shanebp
Instead of checking for login count, and binding the function to 『wp_head』 which will run on every page load, it would be more resource efficient to bind the function to the 『wp_login』 action which will run once; when the user logs into the site. If you want to get really technical – which the computer engineer in me always does – you could argue that the process has been reduced from a time complexity of O(n) to O(n/n) = O(1) where n = the # of page loads from the user. A simple but substantial modification. Rock On @shanebp!
add_action('wp_login','s2_profile_field_update',10,2);
function s2_profile_field_update()
{
global $current_user;
get_currentuserinfo();
if( current_user_is("s2member_level2") )
{
if(xprofile_get_field_data('Nationality',$current_user->id) == '' && get_user_field('nationality') != '')
{
xprofile_set_field_data('Nationality', $current_user->id, get_user_field('nationality'));
}
}
}
I』ll post more as I gather it. But in the mean time I hope this helps some people.
M

會員類型

會員類型

Codex Home → Developer Resources → Member Types
Member Types

BuddyPress 2.2 introduced the concept of member types. This functionality is outlined below.
Registering member types
BuddyPress itself does not register any member types. Plugins and themes can register member types using the bp_register_member_type() or the bp_register_member_types() function:
function bbg_register_member_types() {
bp_register_member_type( 'student', array(
'labels' => array(
'name' => 'Students',
'singular_name' => 'Student',
),
) );
}
add_action( 'bp_register_member_types', 'bbg_register_member_types' );

The first parameter of bp_register_member_type() is a string identifier for the member type, used internally by BP as the canonical name of the type. This name should be unique. The second parameter is a list of generic config arguments.
As of BP 2.2, only the 『labels』 parameter is supported. Future versions of BuddyPress will add additional parameters for better customization and development.
Registering a member type will also enable a meta box so administrators can set a member』s type when editing a user』s 「Extended Profile」 in the WP admin dashboard.
Member Specific Directory
BuddyPress 2.3 introduces the member-type-specific directories. It adds the new 『has_directory』 argument for bp_register_member_type() allowing developers to specify whether a list of members matching a given type 『foo』 should be available at http://example.com/members/type/foo/. A slug can be passed to 『has_directory』 to customize the URL used for the member type』s directory.
function bbg_register_member_types_with_directory() {
bp_register_member_type( 'student', array(
'labels' => array(
'name' => 'Students',
'singular_name' => 'Student',
),
'has_directory' => 'custom-name'
) );
}
add_action( 'bp_register_member_types', 'bbg_register_member_types_with_directory' );

Note that plugins registering member types must do so at the new hook 『bp_register_member_types』 in order to be able to customize the 『has_directory』 value (from its default of true). bp_has_members() automatically detects the presence of a member type in a URL. When no member type of the form example.com/members/type/foo/ is found, URLs of the form example.com/members/?member_type=foo will be detected.
Querying by member type
A common task is to retrieve a list of members of a given type (or set of types). bp_has_members() and BP_User_Query accept a 'member_type' parameter, which can be a single member type or an array/comma-separated list of member types. This will filter query results to those members matching the type. Example:
// Fetch all students and teachers.
$member_args = array(
'member_type' => array( 'student', 'teacher' ),
);
if ( bp_has_members( $member_args ) ) { // ...

Fetching and setting individuals』 member types
When BuddyPress detects that member types have been registered, it will display a Member Type metabox on the user』s Community Profile in Dashboard > Users. Administrators can use this interface to view or change a user』s member type.
BuddyPress also provides simple functions for fetching and setting member types programatically. To get the member type of a user, use bp_get_member_type():
// Get the member type of user 5412.
$member_type = bp_get_member_type( 5412 );

Set a user』s member type using bp_set_member_type():
// Set the member type of user 5412 to 'student'.
$member_type = bp_set_member_type( 5412, 'student' );

修改註冊表單

修改註冊表單

Codex Home → Getting Started → User Submitted Guides → Modifying the Registration Form
Modifying the Registration Form

Once you』ve installed WordPress and BuddyPress, created WordPress pages for BuddyPress to use for Registration and Activation, and then enabled 「Anyone can register」 (under Settings > General > Membership), you』re ready to let users sign up for your new site.
Tip: If you』re already logged in to your new site, visiting mysite.net/register will redirect you to the site home page. Not to worry, that』s the expected behavior, since there』s no point in registering if you』re already registered, right? So fire up a second browser that』s not logged into the site, and point it at your registration page. By default, it』ll look something like this.

The section 「Account Details」 is the portion required for WordPress; the other portion, 「Profile Details,」 is the part BuddyPress adds.

BuddyPress offers a tool to customize the Profile Details section. You can access it by visiting the WordPress administration area and going to Users > Profile Fields. The only field that appears by default is Name (Primary), which is a required field. This field serves as the user』s display name on the site; it is displayed at the top of the user』s profile and also in activity items.

Profile fields can collect a variety of information from your users. BuddyPress 1.8 offers the following field types: text box, multi-line text box, date selector, radio buttons, drop-down select box, multi select box and checkboxes. Let』s add a group of radio buttons to collect your users』 favorite color upon signup. First, click on the 「Add New Field」 button.

In this example, you』ve added the 「field title」 (used as the label on the registration form) and the 「field description」 (used as explanatory text on the registration form if not empty), decided that this isn』t a required field and entered your first color option.

You might need more options, so you can click the link 「Add another option」 to add more options until you』re satisfied.

Whoops, if you didn』t enter the colors in the right order, you can click and drag the options to correct the order. If you need to remove an option, you can click the [x] to the right of the option.

Now you can set the default visibility setting, add an option for the user to override the visibility settings, and save the new field.

The new field appears in the form administration area. Using your other browser (the one that isn』t logged into the site), check your work by reloading the registration form.

You can change the order the profile fields appear on the registration form by clicking and dragging to reorder the fields.

While the new user』s favorite color is interesting, you』ve decided that it』s not important enough to clog up the registration form. Instead, you』d like to have a way for the user to fill that out after she』s registered. This is where profile field groups come into play. Back in the WP profile field admin, notice that the fields are organized under a tab that reads 「Base (Primary)」. This refers to the profile field group that the field belongs to. Fields in the 「Base」 group are displayed on the registration form. You can add another group (or more) to collect other information. We』ll add a new group by clicking on the link 「Add New Field Group」 next to the page title 「Profile Fields.」

Give the new group a title and description, then click on 「Create Field Group.」

Now, you can move the 「Favorite Color」 field from the 「Base」 group to the 「More Details」 group by dragging it to the 「More Details」 tab.

The 「Favorite Color」 field is no longer displayed on the registration form but can be edited via the BuddyPress user profile.

如何通過 WP 用户屏幕將成員添加到羣組

如何通過 WP 用户屏幕將成員添加到羣組

Codex Home → Developer Resources → User Submitted Guides → How to Add Members to a Group via WP Users Screen
How to Add Members to a Group via WP Users Screen

Where we are: users page in the admin screen
What we want to do: add one or n members to a group
What we want to get: an Add to BP Group menu in the Bulk Actions menu box
What we need: a group ID, one or more users. Don』t forget to check the members you want to add!
Where to find the group ID ? Hoovering the 「edit」 button on the groups page will show the ID in the browser bottom left corner, something like http://example.com/wp-admin/admin.php?page=bp-groups&gid=9&action=edit (group ID is 9)

Add this action hook into your theme』s functions.php to provide functionality on a theme basis or add the code to your bp-custom.php file to provide the functionality to your site regardless of theme being used.
Action hook
Caution: This snippet can only be used on servers running PHP 5.3 and above. For previous versions see below please.
function add_users_to_bpgroup() {
if( bp_is_active('groups') ):

if( isset( $_REQUEST['action'] ) && isset( $_REQUEST['bp_gid'] ) && isset( $_REQUEST['allusers'] ) ) {
$group_id = $_REQUEST['bp_gid'];
$users = $_REQUEST['allusers'];

foreach ( $users as $user_id ) {
groups_join_group( $group_id, $user_id );
}
}
//form submission
add_action( 'admin_footer', function() { ?>

jQuery("select[name='action']").append(jQuery('Add to BP Group'));
jQuery("#doaction").click(function(e){
if(jQuery("select[name='action'] :selected").val()=="groupadd") { e.preventDefault();
gid=prompt("Enter a Group ID","1");
jQuery(".wrap form").append('').submit();
}
});

<?php
});

endif;
}
add_action ( 'load-users.php', 'add_users_to_bpgroup' );

Use this if your server is running PHP

jQuery("select[name='action']").append(jQuery('Add to Group'));
jQuery("#doaction").click(function(e){
if(jQuery("select[name='action'] :selected").val()=="groupadd") { e.preventDefault();
gid=prompt("Enter a Group ID","1");
jQuery(".wrap form").append('').submit();
}
});

<?php
};
add_action( 'admin_footer', 'add_users_to_bpgroup_js' );

在成員個人資料上顯示個人資料字段

在成員個人資料上顯示個人資料字段

Codex Home → BuddyPress Theme Development → User Submitted Guides → Displaying Extended Profile Fields on Member Profiles
Displaying Extended Profile Fields on Member Profiles

BuddyPress has some nice built-in tools for collecting data from your members. You』ll be calling the 「extended profile data」 or 「xProfile」 in BuddyPress-speak in your theme. You can retrieve and display this data without modifying template files by attaching a new function to an existing action hook provided by BuddyPress.
For example, Carlos has registered your site and filled out the 「Preferred Color」 xProfile field you added in the profile form you built. And you』d like to display his preference in the header of his member profile. His member profile looks like this by default.

You can add Carlos』 color preference to the profile header by attaching a new function to a hook that BuddyPress provides for you to use. (Read more about action hooks.)
Looking through the BuddyPress template files, you』ll find a file called member-header.php: wp-content/plugins/buddypress/bp-templates/bp-legacy/member-header.php. In that file, look for a line which starts with do_action(…) for the right place to hook your new function to. Line 56 includes 'do_action( 'bp_profile_header_meta' )'. You can add the new code in your theme』s functions.php file, following the example provided at the WordPress Codex: add_action( $hook, $function_to_add, $priority, $accepted_args );
So you will start with:
add_action( 'bp_profile_header_meta', 'display_user_color_pref' );
function display_user_color_pref() {
//This is where the code to display the user data will go.
}

Then you』ll use the BuddyPress function bp_profile_field_data() to retrieve and display the preference. The function bp_profile_field_data fetches and prints the value to screen (like the_content() does) and expects arguments in an array like this:
$args = array(
'field' => 'Favorite Color', // Field name or ID.
'user_id' => bp_displayed_user_id() // Default
);

Since you want to show the color preference of the displayed user (the member whose profile you』re viewing) and bp_profile_field_data uses that member』s ID for its default, you only need to specify the ID or field name of the extended profile field. You can check this value by visiting the Users > Profile Fields page in the WordPress admin. The field name is displayed as the field』s title, and, if you hover over 「Edit,」 the field』s ID is visible in the url: http://example.com/wp-admin/users.php?page=bp-profile-setup&group_id=2&field_id=2&mode=edit_field

In this case, you can use 『Favorite Color』 or the ID, 2:
function display_user_color_pref() {
echo 'I choose this color: ';
$args = array(
'field' => 'Favorite Color', // Field name or ID.
);
bp_profile_field_data( $args );
}

or
function display_user_color_pref() {
echo 'I choose this color: ';
$args = array(
'field' => 2, // Integers do not need to be enclosed in quotes.
);
bp_profile_field_data( $args );
}

But there』s a snag: what if the user didn』t input a favorite color?

You can use the function bp_get_profile_field_data instead to retrieve the value. Then, if there is a value, you』ll be able to display it. The complete code:
add_action( 'bp_profile_header_meta', 'display_user_color_pref' );
function display_user_color_pref() {
$args = array(
'field' => 'Favorite Color', // Field name or ID.
);
$favorite_color = bp_get_profile_field_data( $args );

if ($favorite_color) {
echo 'I choose this color: ' . $favorite_color;
}

}

If the member』s favorite color isn』t specified, then the function outputs nothing.

BP 默認主題 – BP 1.9 向前發展

BP 默認主題 – BP 1.9 向前發展

Codex Home → BuddyPress Theme Development → BP Default Theme – moving forward with BP 1.9
BP Default Theme – moving forward with BP 1.9

Updated BP default theme usuage for BP 1.9 onwards

The BP default theme has served a hugely useful purpose in providing a true out of the box experience for users, allowing for a standard to work from either in re-skinning or for building child themes from. With the successful rollout of the 『Theme Compatibility』 functionality in BP 1.7 a decision was made by the core development team that it was time to officially retire the default bundled theme from the core application. As of BP 1.9 users will note that the listing of the bp-default theme is removed from the WP 『Appearance > Themes』 screens (although it will still appear if you currently use the theme)

What does this mean?
In terms of future development of the theme, this will be limited to providing critical fixes and security updates where necessary but there will be no further development on the theme template files. The theme will continue to be physically bundled in the core download for the immediate future but it is envisioned that at some point the theme files will be removed altogether and hopefully be provided as a standalone theme downloaded from the WP theme repo.
How do these changes affect current theme use?
Have no worries, if you currently use the default theme on your site things will continue to work just as before. BP has the provision to check whether bp-default is activated or whether a theme has overloaded bp-default templates to the top level of their theme and will then disable theme compatibility mode.
There is one important change in behaviour to take into account if you are currently using bp-default and you need to revert to another theme for testing you will find the option to select bp-deault has been removed, don』t panic though to ensure you can still change themes and re-select bp-default you will need to add a simple one line piece of code

?1add_filter( 'bp_do_register_theme_directory', '__return_true' );

Add this line to your bp-custom.php file located in the WP plugins directory ( this file does not exist by default and needs to be manually created and must begin with <?php at the very top of the file.)

Related Resources

Official Announcement: The Future Of The BP-Default Theme

防止垃圾郵件發送者註冊

防止垃圾郵件發送者註冊

Codex Home → Getting Started → User Submitted Guides → Preventing Spammer Registration
Preventing Spammer Registration

Spammers and sploggers pose a serious risk to online communities. Without some protection in place, your fledgling community runs the risk of being overrun by spammers trying to sell fake Uggs and Oakleys. Since fake users can easily make up 98% of all new user account requests, it』s useful to have a game plan for stopping or slowing these fake registrations.
BuddyPress by default requires a user to activate his account via an e-mail sent to the address provided at signup. This simple check will weed out the sploggers and spammers who are using e-mail addresses harvested from the web that they do not have access to, but will not stop users who do have access to a working e-mail address.
WangGuard works by checking new users』 e-mail addresses against a database of e-mails that have been used by spammers on other sites. If the new request uses a known bad address, WangGuard will prevent the user from registering. In addition, it adds some tools that allow your users to flag spam users.
If you』d like to be a little more hands-on, BuddyPress Registration Options requires that a site administrator approve each new registration request. (This plugin will work with WangGuard.)
There are simple changes you can make to the registration form to help identify spambots, too.
Honeypots work by creating hidden fields on the registration form that spam bots can』t resist, then checking for input in those fields upon form submission. 「Humanity tests」 ask the user to respond to a question that should stump a spambot, for example, 「What color is snow?」. Finally, CAPTCHAs are ubiquitous and challenge the user to figure out what letters are shown in a distorted image. Which of these options you choose (you could technically employ all three) is a matter of preference. Honeypots have the advantage of being the least intrusive; 「real」 users won』t even know they』re there. Humanity tests might surprise your users because they』re unusual, but stop spambots effectively. CAPTCHAs are everywhere, so, while they might be annoying, at least they annoy your users in a familiar way. These three strategies will only stop spambots, though; human spammers will be able to defeat any of them.

僅在您的插件需要時才將腳本或樣式排入隊列

僅在您的插件需要時才將腳本或樣式排入隊列

Codex Home → BuddyPress Plugin Development → Enqueueing Scripts or Styles only when your plugin needs it
Enqueueing Scripts or Styles only when your plugin needs it

Using Javascipt or CSS in BuddyPress plugins are interesting ways to take care of the user experience. I think, as a plugin author, you need to have two concerns :

you might not be the only one to use Javascript, other plugins can be activated in the community website,
your CSS rules might not get along with the activated theme

As a result, i advise you to :

enqueue your Javascript or CSS only when your plugin needs it,
allow the theme to override your CSS rules

To illustrate an usage example, you can test the following tutorial. It comes with a BuddyPress plugin 「boilerplate」 (BuddyPlug) that you will find in the additional resources and will help you to achieve this 「roadmap」:
Steps

Choose the best hook to enqueue your scripts
Build your own conditional tags
Allow the theme to override your stylesheet
Additionnal resources

Choose the best hook to enqueue your scripts
Depending on the context, BuddyPress offers two hooks to rely on in order to safely load your scripts. The first one is bp_enqueue_scripts for enqueueing your script on the front end, here』s an example on how to use it from your plugin』s class:
class BuddyPlug {

/* focusing on bp_enqueue_script */

private function __construct() {
$this->setup_globals();
$this->setup_hooks();
}

private function setup_globals() {
// let's define some globals to easily build the url to your scripts
$this->version = '1.0.0';
$this->file = __FILE__;

// url to your plugin dir : site.url/wp-content/plugins/buddyplug/
$this->plugin_url = plugin_dir_url( $this->file );

// url to your plugin's includes dir : site.url/wp-content/plugins/buddyplug/includes/
$this->includes_url = trailingslashit( $this->plugin_url . 'includes' );

// url to your plugin's js dir : site.url/wp-content/plugins/buddyplug/includes/js/
$this->plugin_js = trailingslashit( $this->includes_url . 'js' );

// url to your plugin's css dir : site.url/wp-content/plugins/buddyplug/includes/css/
$this->plugin_css = trailingslashit( $this->includes_url . 'css' );

$this->component_id = 'buddyplug';
$this->component_slug = 'buddyplug';
}

private function setup_hooks() {
// As soon as WordPress meets this hook, your cssjs function will be called
add_action( 'bp_enqueue_scripts', array( $this, 'cssjs' ) );
}

public function cssjs() {
// Your css file is reachable at site.url/wp-content/plugins/buddyplug/includes/css/buddyplug.css
wp_enqueue_style( 'buddyplug-css', $this->plugin_css . 'buddyplug.css', false, $this->version );
// Your script file is reachable at site.url/wp-content/plugins/buddyplug/includes/js/script.js
wp_enqueue_script( 'buddyplug-js', $this->plugin_js . 'script.js', array( 'jquery' ), $this->version, true );
}
}

As you can see, your function cssjs() waits for bp_enqueue_scripts before using the two WordPress functions to load your style (wp_enqueue_style()) and your script (wp_enqueue_script()). At this point, your stylesheet and your javascript will load everywhere on the front end of the site.
The second one is bp_admin_enqueue_scripts for enqueueing your script within the WordPress Administration screens. If for instance your plugin is using a settings page, it can be interesting to load some extra javascript. Concerning CSS, a good practice, in this area, is to use the WordPress Administration markup so that your plugin administration pages are styled the same way than the other part of the Administration. That』s why, the following example does not enqueue a stylesheet:
class BuddyPlug {

/* focusing on bp_admin_enqueue_scripts */

private function setup_hooks() {
add_action( 'bp_enqueue_scripts', array( $this, 'cssjs' ) );

// As soon as WordPress Administration meets this hook, your admin_scripts function will be called
if( is_admin() )
add_action( 'bp_admin_enqueue_scripts', array( $this, 'admin_scripts' ) );
}

public function admin_scripts() {
// Your script file is reachable at site.url/wp-content/plugins/buddyplug/includes/js/admin.js
wp_enqueue_script( 'buddyplug-admin-js', $this->plugin_js .'admin.js', array( 'jquery' ), $this->version, 1 );
}
}

In the above code, your function admin_scripts() waits for bp_admin_enqueue_scripts before enqueueing your script (wp_enqueue_script()). At this point, your javascript will be loaded in every Administration screens.
Build your own conditional tags
Your plugin do not need to play on every page of the community site. To avoid any troubles with other plugins, it』s best you add some control on where your scripts are loaded. The 「where」 are the areas your BuddyPress plugin creates. For instance, it could be:

A new component, using the BP_Component API
An extension of a core component
A new group extension, using the BP_Group_Extension API
Your plugin』s setting page in the Administration

The core file /buddypress/bp-core/bp-core-template.php contains some useful functions to help you identify your plugin』s areas before enqueueing your javascript or your css. When creating a new component, you can build a directory page, in this case your first conditional tags will be:
function buddyplug_is_current_component() {
/*
buddyplug_get_component_id() is a function that returns your component id ($this->component_id in BuddyPlug class)
for instance the activity component id is 'activity'.
In this example the function simply returns 'buddyplug'
I advise you to observe how the component.php file of the BuddyPlug plugin
is creating its component
*/
return bp_is_current_component( buddyplug_get_component_id() );
}

function buddyplug_is_directory() {
if( buddyplug_is_current_component() && bp_is_directory() )
return true;

return false;
}

So in order to only load script in your directory pages you simply need to check for buddyplug_is_directory() before enqueueing your script. If you use the BuddyPlug plugin, it will show you the result of these two functions, here is a screen capture to illustrate.
Loading Javascript in a directory page.
 
If you simply check for buddyplug_is_current_component(), then your script will also load on the plugin』s tab in the members profiles.
Loading Javascript for member's profile.
 
Your plugin can also extend the settings component to add a new tab to it to let the member customize its behavior. The following code creates a new conditional tag that you will be able to use to be sure your script is loaded in this area
function buddyplug_is_user_settings() {
/*
buddyplug_get_component_slug() is a function that simply returns the slug of the plugin ($this->component_slug in BuddyPlug class)
in this case it's 'buddyplug'
it means the sub navigation added to the settings component is reachable at
site.url/members/userlogin/settings/buddyplug
I advise you to have a look at the setup_settings_bp_nav() function in the component.php file
of the BuddyPlug plugin to see how the sub navigation is created.
*/
if( bp_is_settings_component() && bp_is_current_action( buddyplug_get_component_slug() ) )
return true;

return false;
}

Here』s a screen capture of this particular tab:
Loading JS in a Tab added to settings component
 
If you are using the Group Extension API, you can build some new conditional tags to check if the Group main tab, the Group admin edit tab, or the creation step of your plugin are loaded.
/**
* The Group Main tab for your plugin
*/
function buddyplug_is_group_front() {
if( bp_is_single_item() && bp_is_groups_component() && bp_is_current_action( buddyplug_get_component_slug() ) )
return true;

return false;
}

/**
* The Group creation step for your plugin
*/
function buddyplug_is_group_create() {
if( bp_is_group_creation_step( buddyplug_get_component_slug() ) )
return true;

return false;
}

/**
* The Group Admin Edit tab for your plugin
*/
function buddyplug_is_group_edit() {
if( bp_is_group_admin_page() && bp_is_action_variable( buddyplug_get_component_slug(), 0 ) )
return true;

return false;
}

/**
* Are we in your plugin's group area ?
*/
function buddyplug_is_group_area() {
if( buddyplug_is_group_front() || buddyplug_is_group_create() || buddyplug_is_group_edit() )
return true;

return false;
}

This is a screen capture that illustrates the buddyplug_is_group_edit() conditional tag
Loading JS in Group Admin Edit tab
 
Now, as an example, let』s imagine you wish to only load your script when on any of the area your plugin』s has created on the front end, then your function cssjs() in the BuddyPlug class could be :
public function cssjs() {
if( ( bp_is_active( $this->component_id ) && buddyplug_is_component_area() ) || ( bp_is_active( 'groups' ) && buddyplug_is_group_area() ) ) {
// Your css file is reachable at site.url/wp-content/plugins/buddyplug/includes/css/buddyplug.css
wp_enqueue_style( 'buddyplug-css', $this->plugin_css . 'buddyplug.css', false, $this->version );
// Your script file is reachable at site.url/wp-content/plugins/buddyplug/includes/js/script.js
wp_enqueue_script( 'buddyplug-js', $this->plugin_js . 'script.js', array( 'jquery' ), $this->version, true );
}
}

Note that we check if the groups component is active using the BuddyPress function bp_is_active().
As the last step of this part, you need to also make sure the javascript your plugin is using for its settings page is only loaded on this particular page. To do so you could use the $_GET['page'] variable or use the WordPress get_current_screen() function, or when the 1.9 version will be released simply check for the bp_admin_enqueue_scripts argument. See the following example:
class BuddyPlug {

/* focusing on bp_admin_enqueue_scripts */

private function setup_hooks() {
if( is_admin() ) {
add_action( bp_core_admin_hook(), array( $this, 'admin_menus' ) );
add_action( 'bp_admin_enqueue_scripts', array( $this, 'admin_scripts' ), 10, 1 );
}
}

/**
* Creates the admin pages
*/
public function admin_menus() {

$this->hook_suffixes[] = add_submenu_page(
$this->settings_page,
__( 'BuddyPlug Options', 'buddyplug' ),
__( 'BuddyPlug Options', 'buddyplug' ),
'manage_options',
'buddyplug',
'buddyplug_admin_settings'
);

/*
Using an array can help you get the screen ids of each of your
administration menus...
$this->hook_suffixes[] = add_menu_page()
*/
}

/**
* Eqnueues script
*/
public function admin_scripts( $hook = '' ) {
if( empty( $hook ) )
$hook = bp_core_do_network_admin() ? str_replace( '-network', '', get_current_screen()->id ) : get_current_screen()->id;

/* only loads the script if you are in one of your plugin's Administration screen
if( in_array( $hook, $this->hook_suffixes ) ) {
wp_enqueue_script( 'buddyplug-admin-js', $this->plugin_js .'admin.js', array( 'jquery' ), $this->version, 1 );
}

}

}

Example of use of a JS in your plugin』s settings page
Allow the theme to override your stylesheet
Finally, like BuddyPress does (see first link of the Additional resources section), you definatively should allow the theme to override the main css of your plugin. The very great reason is that, this way, the community Administrator will be able to add the final touch to your plugin that will make it look perfect in his theme
class BuddyPlug {

/* focusing on allowing theme to override the plugin's css file on front end */

public function cssjs() {

//Search in theme's folder
$css_datas = (array) $this->css_datas();

// before enqueueing the best style
wp_enqueue_style( $css_datas['handle'], $css_datas['location'], false, $this->version );

}

/**
* The theme can override plugin's css
*/
public function css_datas() {
$file = 'css/buddyplug.css';

// Check child theme
if ( file_exists( trailingslashit( get_stylesheet_directory() ) . $file ) ) {
$location = trailingslashit( get_stylesheet_directory_uri() ) . $file ;
$handle = 'buddyplug-child-css';

// Check parent theme
} elseif ( file_exists( trailingslashit( get_template_directory() ) . $file ) ) {
$location = trailingslashit( get_template_directory_uri() ) . $file ;
$handle = 'buddyplug-parent-css';

// use our style
} else {
$location = $this->includes_url . $file;
$handle = 'buddyplug-css';
}

return array( 'handle' => $handle, 'location' => $location );
}

}

Additional resources

wp_enqueue_script() in WordPress Codex
wp_enqueue_style() in WordPress Codex
Add BuddyPress styles to a theme
You can learn more about BP_Component from its Codex page
You can learn more about BP_Group_Extension from its Codex page
You can download the BuddyPlug example plugin from his github repository

自定義 BuddyPress 頭像

自定義 BuddyPress 頭像

Codex Home → BuddyPress Theme Development → User Submitted Guides → Customizing BuddyPress Avatars
Customizing BuddyPress Avatars

The BuddyPress core allows for a number of ways for you to customize the size and appearance of user avatars. In this tutorial we』ll show you which files to edit in order to make changes to avatars. We』ll also walk through several example customizations.
Default BuddyPress Avatar Sizes
Before customizing avatars, it』s important to know the default values. BuddyPress essentially has two sets of avatar sizes:

Thumb – defaults to 50px square
Full – defaults to 150px square

Examples of the 50px thumbnails can be seen in activity stream entries as well as the members/groups directory pages. The full size is used for the avatar displayed on user profile pages.

How to Change BuddyPress Avatar Sizes
BuddyPress allows for changing the default avatar sizes using a constant. These constants are set up in /bp-core/bp-core-avatars.php. If you want to change their values, you will need to create and/or edit your bp-custom.php file. Here are the available options:
define ( 'BP_AVATAR_THUMB_WIDTH', 50 );
define ( 'BP_AVATAR_THUMB_HEIGHT', 50 );
define ( 'BP_AVATAR_FULL_WIDTH', 150 );
define ( 'BP_AVATAR_FULL_HEIGHT', 150 );
define ( 'BP_AVATAR_ORIGINAL_MAX_WIDTH', 640 );
define ( 'BP_AVATAR_ORIGINAL_MAX_FILESIZE', $max_in_kb );

Let』s walk through a few examples. Perhaps you want to increase avatar sizes across the board. Paste the defines for the thumb and full avatar sizes into your bp-custom.php file and change the values to whatever size you want.
define ( 'BP_AVATAR_THUMB_WIDTH', 80 );
define ( 'BP_AVATAR_THUMB_HEIGHT', 80 );
define ( 'BP_AVATAR_FULL_WIDTH', 250 );
define ( 'BP_AVATAR_FULL_HEIGHT', 250 );
?>

You can also change the size of the original image that BuddyPress stores, as well as limit the file size the users can upload. This is a good idea if you don』t want users to upload insanely large files as avatars. Add this to your bp-custom.php file and change the values to suit your needs. These are example values:
define ( 'BP_AVATAR_ORIGINAL_MAX_WIDTH', 800 );
define ( 'BP_AVATAR_ORIGINAL_MAX_FILESIZE', 200 );

How to Change the Default BuddyPress Avatar
The default avatar is the one that appear when a user has not yet uploaded his own avatar. If you』re not a fan of the mystery man, here are the constants that you can use to define your own:
define ( 'BP_AVATAR_DEFAULT', $img_url );
define ( 'BP_AVATAR_DEFAULT_THUMB', $img_url );

Change the the constant to include the URL for the location of your new default avatars and add this to your bp-custom.php file.
define ( 'BP_AVATAR_DEFAULT', 'http://example.com/default-avatar.jpg' );
define ( 'BP_AVATAR_DEFAULT_THUMB', 'http://example.com/default-avatar-thumb.jpg' );

To use a default avatar without Gravatar you should also add:
add_filter( 'bp_core_fetch_avatar_no_grav', '__return_true' );

To continue using Gravatar you should add:
add_filter( 'bp_core_avatar_default', function() {
return BP_AVATAR_DEFAULT;
} );

How to Customize BuddyPress Avatars With CSS
When using CSS to manipulate BuddyPress avatars, the most important thing to remember is that you always want to size down from the full or the thumbnail size. If you use CSS to try to size avatars up to a larger size, you will get fuzzy, distorted avatars.
The default BuddyPress theme adds 『avatar『 class to BuddyPress avatars. You can target this class within your BuddyPress child theme in order to make customizations to avatars. For example, let』s say that you want to make all the avatars circles. You might add something like this to your theme』s stylesheet:
img.avatar {
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
-ms-border-radius: 50%;
-o-border-radius: 50%;
border-radius: 50%;
-webkit-box-shadow: 0 1px 0 #fff;
-moz-box-shadow: 0 1px 0 #fff;
box-shadow: 0 1px 0 #fff;
}

All of your BuddyPress avatars will now be circular:

Using Firebug you can determine even more specific classes to target. For example, if you only wanted to change the shape of the main avatar on user profile pages, you could target it using the div#item-header-avatar img.avatar selector instead.
If you implement circular avatars, you may also want to change the shape of the crop pane that is displayed when users are uploading and cropping a new avatar. This CSS, added to your child theme, will change the crop pane to be a circle so that users can accurately preview the new avatar:
#avatar-crop-pane { border-radius: 50%; }

The result will look something like this:

Please note that these examples are applicable to a child theme of the default BuddyPress theme. If you』re working with another theme, the classes may be different but the process is the same.
How to Disable Avatar Uploads
Disabling avatar upload for your BuddyPress site is very easy. Navigate to Dashboard >> Settings >> BuddyPress >> Optionss tab and uncheck the box that says 「Allow registered members to upload avatars」.

Disabling uploads will still allow for Gravatars. Support for this service is built in, so your users can still have avatars. While disabling avatar upload limits users』 ability to customize their profiles, the advantage for you is that Gravatar hosts all of the avatars.