在插件中使用 BP Theme CompatCodex Home → BuddyPress Plugin Development → Using BP Theme Compat in Plugins
Using BP Theme Compat in Plugins
A BuddyPress plugin can need to display content in several areas of a BuddyPress powered community :
In its own directory
In the member』s profile pages
In groups
The goal of this tutorial is to show you a way to take benefit of the magic that will be introduced in the next major release of BuddyPress (version 1.7) to maximize theme compatibility for BuddyPress content and for the content generated by your plugin.
In Plugin』s main directory.
When using the BP_Component class, we can specify that our plugin will have its own directory area. Here』s a quick reminder :
class BP_Plugin_Component extends BP_Component {
function __construct() {}
function includes() {
// Files to include
$includes = array(
/* some files */
'includes/bp-plugin-screen.php',
/*some other files */
);
parent::includes( $includes );
}
function setup_globals() {
$globals = array(
'slug' => 'some-slug',
'root_slug' => 'some-root-slug',
/* has_directory is set to true in order to setup plugin's main directory */
'has_directory' => true,
'notification_callback' => 'function_to_format_notification',
/* etc... */
);
parent::setup_globals( $globals );
}
function setup_nav() {}
function setup_admin_bar() {}
}
function bp_plugin_load_core_component() {
global $bp;
$bp->bp_plugin = new BP_Plugin_Component;
}
add_action( 'bp_loaded', 'bp_plugin_load_core_component' );
In this example, i』m using the file bp-plugin-screen.php in order to hold all the functions that will allow us to set the needed template for our plugin』s main directory.
So far, in order to indicate to BuddyPress the path to my plugin』s template, i used to filter the bp_located_template hook :
function bp_plugin_load_template_filter( $found_template, $templates ) {
//Only filter the template location when we're on the bp-plugin component pages.
if ( !bp_is_current_component( 'bp-plugin' ) )
return $found_template;
foreach ( (array) $templates as $template ) {
if ( file_exists( STYLESHEETPATH . '/' . $template ) )
$filtered_templates[] = STYLESHEETPATH . '/' . $template;
elseif( file_exists( TEMPLATEPATH . '/' . $template ) )
$filtered_templates[] = TEMPLATEPATH . '/' . $template;
else
$filtered_templates[] = BP_PLUGIN_DIR . '/templates/' . $template;
}
$found_template = $filtered_templates[0];
return apply_filters( 'bp_plugin_load_template_filter', $found_template );
}
add_filter( 'bp_located_template', 'bp_plugin_load_template_filter', 10, 2 );
We first check for our template file in the active theme or in the parent theme, and if nothing was found, we add to the templates array the path to our plugin template folder. Doing so, we allow themes to 「override」 and adapt the template to their design.
This done, in order to tell to BuddyPress to load the required template for my root plugin directory i filter the hook 『bp_screens『 :
function bp_plugin_screen_index() {
// i first check i'm on my plugin directory area...
if ( !bp_displayed_user_id() && bp_is_current_component( 'bp-plugin' ) && !bp_current_action() ) {
bp_update_is_directory( true, 'bp-plugin' );
//... before using bp_core_load_template to ask BuddyPress
// to load the template bp-plugin (which is located in
// BP_PLUGIN_DIR . '/templates/bp-plugin.php)
bp_core_load_template( apply_filters( 'bp_plugin_screen_index', 'bp-plugin' ) );
}
}
add_action( 'bp_screens', 'bp_plugin_screen_index' );
As you can see, when BuddyPress will run the function bp_core_load_template, which is located at line 346 of the /bp-core/bp-core-catchuri.php file (in BuddyPress 1.7-beta1), as soon as it meets the 『bp_located_template『 filter, my function 『bp_plugin_load_template_filter』 will step in to add my plugin template path. This is made possible thanks to line 379 of this file :
// Filter the template locations so that plugins can alter where they are located
$located_template = apply_filters( 'bp_located_template', locate_template( (array) $filtered_templates, false ), $filtered_templates );
In BuddyPress 1.7, this method is still working fine as soon as the community administrator is using the bundled BP Default theme or a child of it. But, if he decides to enjoy the 「BP Theme Compat」 great new feature in order to use any WordPress theme, then the content generated by our plugin will not display the best way.
To maximize this, we need to use the new hook introduced in the 1.7 version : do_action(『bp_setup_theme_compat』) which is located at line 410 of the bp_core_load_template function.
Actually, if BuddyPress haven』t found the required template then this hook is finally fired. Unlike what we』ve done just above, the funny part of this tutorial is that we first won』t tell BuddyPress what template to load if the active theme is not BP Default or a child of it.
In order to check if BP Default, or a child of it, or an eventual BuddyPress theme that is not relying on BP Default is active on the blog, i use this function :
function bp_plugin_is_bp_default() {
// if active theme is BP Default or a child theme, then we return true
// If the Buddypress version is < 1.7, then return true too
if(current_theme_supports('buddypress') || in_array( 'bp-default', array( get_stylesheet(), get_template() ) ) || ( defined( 'BP_VERSION' ) && version_compare( BP_VERSION, '1.7', ' 0,
'post_title' => 'BP Plugin Directory',
'post_author' => 0,
'post_date' => 0,
'post_content' => '',
'post_type' => 'bp_plugin',
'post_status' => 'publish',
'is_archive' => true,
'comment_status' => 'closed'
) );
}
/**
* Filter the_content with bp-plugin index template part
*/
public function directory_content() {
bp_buffer_template_part( 'bp-plugin' );
}
}
new BP_Plugin_Theme_Compat ();
Thanks to this step, we just made sure that BuddyPress will look for the bp-plugin template in the WordPress Theme or in the BP Legacy templates before trying to load it.
However, unless the active theme thought about adding this template, it won』t find it as it won』t check our plugin』s templates folder. We need to reference our plugin template folder first.
To do so, we can add a filter on the 「bp_get_template_stack」 hook in order to store our plugin path into the BuddyPress template paths :
function bp_plugin_add_template_stack( $templates ) {
// if we're on a page of our plugin and the theme is not BP Default, then we
// add our path to the template path array
if ( bp_is_current_component( 'bp-plugin' ) && !bp_plugin_is_bp_default() ) {
$templates[] = BP_PLUGIN_DIR . '/templates/';
}
return $templates;
}
add_filter( 'bp_get_template_stack', 'bp_plugin_add_template_stack', 10, 1 );
Doing so we make sure that if our template is not found in the WordPress active theme or in bp-legacy, it will be found in our plugin』s template folder. Finally we just need to adapt our plugin template in BP_PLUGIN_DIR . 『/templates/』 in order to strip the get_header, get_sidebar, and get_footer calls and to simply put our output into the new container tag 『
』. Now, if our template needs to load other template parts, we can use the new function bp_get_template_part to load it. Personally, i use a function that allows me to alternatively handle BP default or any WordPress theme in order to display my plugin content the best way :
function bp_plugin_locate_template( $template = false ) {
if( empty( $template ) )
return false;
if( bp_plugin_is_bp_default() ) {
locate_template( array( $template . '.php' ), true );
} else {
bp_get_template_part( $template );
}
}
In the member』s profile pages
We have two choices to load our plugin template in this area. First, we can take benefit of the different hooks bundled in the members/single/plugins.php BuddyPress template to inject our plugin』s content in its member area. Three hooks can be used :
do_action( 'bp_template_content_header' );
do_action( 'bp_template_title' );
do_action( 'bp_template_content' );
Back on our component class, when setting our plugin user navigation, we specify the screen function to play :
class BP_Plugin_Component extends BP_Component {
function __construct() {}
function includes() {}
function setup_globals() {}
function setup_nav() {
$main_nav = array(
'name' => __( 'BP Plugin' ),
'slug' => BP_PLUGIN_SLUG,
'position' => 80,
/* main nav screen function callback */
'screen_function' => 'bp_plugin_main_screen_function',
'default_subnav_slug' => 'bp-plugin-subnav'
);
// Add a few subnav items under the main tab
$sub_nav[] = array(
'name' => __( 'BP Plugin' ),
'slug' => 'bp-plugin-subnav',
'parent_url' => 'link to the parent url',
'parent_slug' => 'parent slug',
/* sub nav screen function callback */
'screen_function' => 'bp_plugin_main_screen_function',
'position' => 10,
);
parent::setup_nav( $main_nav, $sub_nav );
}
function setup_admin_bar() {}
}
Now in our bp-plugin-screen.php file, we need to write some code for our screen function in order to add actions when the three different hooks will be fired to display our content, for example :
function bp_plugin_main_screen_function {
add_action( 'bp_template_content_header', 'bp_plugin_menu_header' );
add_action( 'bp_template_title', 'bp_plugin_title' );
add_action( 'bp_template_content', 'bp_plugin_content' );
bp_core_load_template( apply_filters( 'bp_core_template_plugin', 'members/single/plugins' ) );
}
function bp_plugin_menu_header() {
_e( 'Menu Header' );
}
function bp_plugin_title() {
_e( 'Plugin title' );
}
function bp_plugin_content() {
_e( 'Plugin content');
}
We can use another approach by using a new template from our plugin』s template directory. However, unlike what we』ve accomplished earlier when we hooked 『bp_setup_theme_compat『 to display our root plugin directory content, we』ll use another method to modify the template to load as whatever happens, BP_Members_Theme_Compat will buffer the members/single/plugins template. So in our screen function, we first use the bp_core_load_template as it will be used in the BP Default case and as it will finally fire the bp_setup_theme_compat hook for any WordPress theme. Then we use our BP Default check in order to add a filter (if it returns false) to the bp_get_template_part function.
function bp_plugin_main_screen_function(){
bp_core_load_template( apply_filters( 'bp_plugin_main_screen_function', 'bp-plugin-main-user-template' ) );
//if BP Default is not used, we filter bp_get_template_part
if( !bp_plugin_is_bp_default() )
add_filter('bp_get_template_part','bp_plugin_user_template_part', 10, 3 );
}
function bp_plugin_user_template_part( $templates, $slug, $name ) {
if( $slug != 'members/single/plugins' )
return $templates;
return array( 'bp-plugin-main-user-template.php' );
}
Our bp_plugin_user_template_part will override the members/single/plugins.php BuddyPress template by our bp-plugin-main-user-template.php plugin template.
Finally, don』t forget to create the template BP_PLUGIN_DIR . 『/templates/bp-plugin-main-user-template.php』
In Group pages
here we just need to rely on the display function of the BuddyPress Group Api. In order to make sure our content will load the best way in BP Default or a child of it and any WordPress theme we can use our custom bp_plugin_locate_template function.
class BP_Plugin_Group extends BP_Group_Extension {
/** other function of group API **/
function display() {
bp_plugin_locate_template( 'bp-plugin-group-template' );
}
/** other function of group API **/
}
Finally, don』t forget to create the template BP_PLUGIN_DIR . 『/templates/bp-plugin-group-template.php』
Codex 标准和指南Codex Home → Participate and Contribute → Codex Standards & Guidelines
Codex Standards & Guidelines
If you are considering contributing to the codex this simple guide is here to help you with the formatting of pages and standards & conventions to follow to keep a set appearance to pages.
The Codex is curated by a team of volunteers they will check and verify articles for accuracy and adherence to Codex Standards, this is in order to maintain a consistent quality of article and standard throughout the codex. If you notice any articles of concern or think something is outdated or needs checking please contact one of the team members, if you are sure an article contains content that needs attention you may edit it and add a warning to the top of the article – please see the bottom of this page for markup to be copied and used in such circumstances.
Please note: All entries to the Codex are covered by the GNU General Public Licence. All entries may be edited or altered by other contributors.
Sections
How to Create a New Codex Article
How to Edit/Update an Article in the Codex
Codex General Guidelines
Codex Conventions
Formatting Guide
Adding article header messages
How to Create a New Codex Article
Log in using your WordPress username and password.
Click on the 「Create New Page」 link under the header or click on the 「+New > Page」 link on the WP Toolbar
Add the Title of your article
Add the article metas: Versions, Components, Types and Context. Meta boxes are located on the screen』s right sidebar
Add your article in the appropriate codex section in the Page Attributes meta box under the Context box.
For reference, please go to the BuddyPress Codex Table of Contents which is updated regularly to guide you where to place your article
Add content of your article. Check that it follows the Codex General Guidelines, Codex Conventions, and Formatting guides posted below for your reference
After you』re done, click on the 「Publish」 button
How to Edit/Update an Article in the Codex
Log in using your WordPress username and password
Navigate to the page you want to edit/update
Click on the 「Edit Page」 link under the header of the page or click on the 「Edit Page」 link on the WP Toolbar
After you have made the edit/update, please double-check that the Versions, Components, Types and Context are correct and updated as well
Click on the 「Update」 button in the Publish meta box
General Guidelines
Broad guidelines on writing for the BuddyPress Codex
When writing articles please use the second-person point of view to address the reader. e.g. 「Now navigate to your」 Rather than 「Now navigate to our「
When writing technical articles (functions, actions, etc.) please use the draft template you will find in the dashboard, copy and paste it』s body outline markup to your new post
Please keep styling to a minimum, avoid inline styling of elements unless to provide something like a color highlight if thought necessary to lend further emphasis to a piece of text e.g styling a warning in red Ensure you have backed up your DB. Please use elements sparingly , are typographic conventions and used to embolden text and italicize text for foreign & scientific words/phrases; , are to lend weight or importance to a word or phrase i.e 』em』 is not used simply to visually style text in italics
Links: External resource links: Provided to the bottom of the article framework is a section for links to external resources, please use this section for any links to resources that help further however please ensure that these links are additional resources and that your article does not depend on them for all or any part of your article explanation, the reasoning here is external links are not guaranteed to always be available and if the article relies on them and they are down then the article is effectively useless for users. Links that are not related directly to the article content are to be avoided and if found will be removed
Images: Do add images to articles where they help to illustrate your points or explanations, nothing helps illustrate things better than a timely graphic, screen shots of BuddyPress or WordPress screens help to show the reader layouts. As with links please avoid calling remote images, always upload to the media library, and embed. If uploading images please ensure you have the right to do so and are not infringing on any copyrights that may exist. Any images thought to be or that are under copyright will be removed from pages
Creating pages: When creating pages , please ensure you select a suitable 『Version』 tag, and optionally select from available 『Components』 tags & 『Types』. Please only select a parent category from the available parent sections, We request that authors DO NOT create new pages that act as parent pages for their article/s, this is to ensure the integrity of the codex structure, however it may be possible to expand the structure if thought beneficial, but please make a request for this to one of the Codex curation team members for consideration
Codex Conventions
Website Example Names: Always use example.com, example.org or example.net wherever you need to state a domain as an example. This is per RFC 2606.
Admin: The username admin describes the default administrator account of a WordPress installation in examples (admin should never be used on a live site due to negative security implications).
Using people』s names in examples: When a name is needed for an ordinary, non-admin user, or a person, use Harriet as the first name, and Smith as the last name
Administration Panels: The WordPress interface is called Administration Panels not admin panels or dashboard. Dashboard is a specific panel within Administration Panels. Individual panels are also called Administration Screens
WordPress is spelled WordPress: WordPress is spelled with two capital letters: WordPress
BuddyPress is spelled BuddyPress: BuddyPress is spelled with two capital letters: BuddyPress
With thanks to WP codex guidelines for borrowed bullet points: WP Codex:Guidelines
Formatting Guide
If writing a technical guide please use the template format provided in this draft document ( copy paste to new page ) Codex template – technical examples layout
1. Heading Tags:
Use h3 – h6. For example, on this page h3 is used for 「Sections」 above and for the title of this Section, 「Style and Formatting「.
2. Code examples: Surround your code with the appropriate shortcodes
[php] your PHP code [/php]
[html] your HTML code [/html]
Also available are bash, shell, css, diff, patch, js, javascript, plain, text, sql and xml and are used in the same format as the previous examples.
N.B: When adding code examples please escape angle brackets with Numeric/Decimal entities rather than 『Named ones, so use &# 060; and &# 062;
3. Lists: Use unordered and ordered lists where appropriate.
4. File names: Surround file names with the code tags
index.php
5. The structure of a technical guide
[Intro]
a brief intro to the guide
[/Intro][Functions]
List the functions, location, params etc.
[/Functions][Your Content]
The content body – explanation/guide.
[/Your content][Example Usage]
Provide a simple example of code use – using pre/code tags.
[/Example Usage][Additional Resources]
Add any links to off site or internal pages that might help further.
[/Additional Resources]
Flagging articles – adding article header messages
Page may be tagged in the body with two 『Notes』
1/ This page is a legacy document (at top of page)
if a page is deemed to be outdated or superseded by BP versions, or changes then it may be marked with this code block
This is Legacy Document
The details in this page have either been updated or are deprecated completely. Legacy Docs are retained for historic reference.
and the page would be re-assigned under the parent section 『legacy』
2/ This page is in need of updating
A page is considered incomplete or needs to be verified for detail.
This page is incomplete or needs checking and verifying.
bp_member_user_id()Codex Home → Developer Resources → Function Examples → bp_member_user_id()
bp_member_user_id()
Description
Get the id of the user in a members loop.
If placed outside of a Members loop, it will be empty.
Usage
bp_member_user_id();
Parameters
None.
Example
Source File
bp_member_user_id() is located in bp-members/bp-members-template.php.
bp_core_get_userlink()Codex Home → Developer Resources → Function Examples → bp_core_get_userlink()
bp_core_get_userlink()
Description
Returns a HTML formatted link for a user with the user』s full name as the link text.
Top
Usage
Top
Parameters
$user_id
(integer) User ID to check.
$no_anchor
(bool) Disable URL and HTML and just return full name. Default false.
$just_link
(bool) Disable full name and HTML and just return the URL text. Default false.
Returns
Returns false when there was no match found, and the link text (string) based on passed parameters.
Top
Example
Top
Source File
bp_core_get_userlink() is located in bp-members/bp-members-functions.php
.htaccess 重定向 FORCE_SSL_ADMINCodex Home → Getting Started → .htaccess redirects for FORCE_SSL_ADMIN
.htaccess redirects for FORCE_SSL_ADMIN
This is a quick reference for anyone that is using FORCE_SSL_ADMIN in their wp-config.php to serve the admin dashboard and user login over https, but would like normal users to browse the frontend over http. BuddyPress implements its own set of redirect to parameters so that normal users are redirected back to the frontend after logging in rather than going straight to the admin dashboard (the default WP behavior). This makes sense as most BP users aren』t going to need to see the dashboard, but when FORCE_SSL_ADMIN is enabled this redirection includes https and causes regular users to browse the frontend over https.
One solution for fixing this is to use .htaccess rules to blanket redirect users who are not browsing the admin dashboard to the http version of your site. Below is some sample .htaccess rewrite rules that should redirect your users to http when they login. Your .htaccess file should be located in your document root, but may vary depending on your configuration.
Make sure that your redirect rules occur before the WordPress section (which is added if you use permalinks). Also, note that the rewrite condition you use to check for https may differ. For example, for some shared hosts you may need to use RewriteCond %{HTTP:X-Forwarded-SSL} on instead.
For more information on .htaccess rules and SSL check out this article.
# This is the additional rewrite section
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule !^wp-(admin/|login.php|includes/|content/)(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress
用户扩展个人资料Codex Home → Administrator Guide → User Extended Profiles
User Extended Profiles
Highlight the best of your community members by creating an unlimited number of Extended Profile (xProfile) Fields and/or groups of Extended Profile Fields custom-made for your social network.
To start creating xProfile fields, go to administration menu Users > Profile Fields. If you have a multisite installation with BuddyPress activated network-wide via Network Admin > Plugins, you』ll find the Profile Fields admin screen via Network Admin > Users > Profile Fields
Sections
Add New xProfile Field
Add New xProfile Field Group
Rearranging xProfile Fields or Field Groups
Add New xProfile Field
Fields marked * are required.
Fields in the 「Base」 (Primary) group will appear on the signup/register page.
Input
Field Title*
Field Description
Is this field required?
Select
Not Required
Required
Field Type:
Select
Single Line Text Box
Multi-line Text Box
Date Selector
Radio Buttons
Dropdown Select Box
Multiple Select Box
Checkboxes
Default Visibility
Options
Anyone (default)
Logged In Users
Admins Only
My Friends
Per-Member Visibility
Options
Let members change this field』s visibility {default)
Enforce the default visibility for all members
Save button, Cancel link
Edit Group button – allows you add, remove, move or change any xProfile field in the specific xProfile Group
Name (Primary)(Required) Field – Nice Name
Edit Field button – opens up a new screen
Input
Field Name (Required)
Field Description
Add New xProfile Field Group
The Add New Field Group button is located beside the Profile Fields component title. Click on the button to create a new Profile Group where you can later add more xProfile Fields
Title of xProfile Field Group
(Field) Group Description
Create Field Group button or Cancel link
Rearranging xProfile Fields or xProfile Field Groups
A. Change order of xProfile Fields within a Profile Field Group:
You can change the order by which xProfile Field/s show up in the Registration Form or in the Member』s Profile area by dragging the field up or down within the field group to the preferred location.
B. Change order of xProfile Field Groups:
You can change the order by which your xProfile Field Groups show up in Member』s Profile area by dragging the Group Tab to the left or right in Users > Profile Fields screen. Remember that only the Base (Primary) Field Group shows up in the Registration Form.
C. Move an xProfile Field from one xProfile Field Group to Another:
1. Click on the xProfile Field Group tab to open the panel where the xProfile Field you want to move is located.
2. Drag that xProfile Field to the xProfile Field Group tab where you want to move the xProfile Field.
3. You can then rearrange the position of the xProfile Field in new field group by dragging up or down to where you want to position the xProfile Field within the new group.