Last active
February 19, 2020 10:40
-
-
Save ylkyrg/bf1504fd7df91438c49e74712227beb5 to your computer and use it in GitHub Desktop.
WP User Profiles + CMB2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* WP User Profiles + CMB2 | |
* | |
* CMB2 user meta doesn't play very nicely with WP User Profiles. This | |
* class is an example of getting them to work together. | |
* | |
* @see https://github.com/CMB2/CMB2 | |
* @see https://github.com/stuttter/wp-user-profiles | |
*/ | |
class WPUserProfilesCMB2 { | |
/** | |
* The cmb2 metabox | |
* | |
* @var CMB2 | |
*/ | |
protected $metabox; | |
/** | |
* Add required hooks | |
* | |
* @return void | |
*/ | |
public function add_hooks() { | |
add_action( | |
'cmb2_init', | |
[ $this, 'add_cmb2_metabox' ] | |
); | |
// In this example the metabox is added to the account page. | |
add_action( | |
'wp_user_profiles_add_account_meta_boxes', | |
[ $this, 'add_wp_metabox' ] | |
); | |
} | |
/** | |
* Add a WP metabox to contain the CMB2 metabox | |
* | |
* CMB2 metaboxes added to users are not contained | |
* within a postbox. | |
* | |
* @return void | |
*/ | |
public function add_wp_metabox() { | |
add_meta_box( | |
'example', | |
'Example', | |
[ $this, 'show_form' ], | |
null, | |
'normal', | |
'high', | |
null | |
); | |
} | |
/** | |
* Set up the CMB2 metabox | |
* | |
* @return void | |
*/ | |
public function add_cmb2_metabox() { | |
$cmb = \new_cmb2_box( | |
[ | |
'id' => 'example_metabox', | |
'title' => 'Example', | |
'screen' => 'users_account_page', | |
'show_on_cb' => [ $this, 'show_on_cb' ], | |
] | |
); | |
$cmb->add_field( | |
[ | |
'name' => 'Example', | |
'id' => 'example', | |
'type' => 'text', | |
] | |
); | |
$this->metabox = $cmb; | |
} | |
/** | |
* Callback for the WP metabox | |
* | |
* CMB2 adds user metaboxes to the 'show_user_profile' and | |
* 'edit_user_profile' hooks. This function mimics how they're added | |
* and is used as a callback to the WP metabox. | |
* | |
* @return void | |
*/ | |
public function show_form() { | |
$hookup = new \CMB2_Hookup( $this->metabox ); | |
if ( $this->metabox->prop( 'cmb_styles' ) ) { | |
$hookup::enqueue_cmb_css(); | |
} | |
if ( $this->metabox->prop( 'enqueue_js' ) ) { | |
$hookup::enqueue_cmb_js(); | |
} | |
$this->metabox->show_form(); | |
} | |
/** | |
* Show on particular admin screen | |
* | |
* This is to stop WP User Profiles outputting the CMB2 form | |
* in its other section. | |
* | |
* @param CMB2 $cmb The cmb2 metabox object. | |
* @return bool | |
*/ | |
public function show_on_cb( $cmb ) { | |
return $cmb->prop( 'screen' ) === get_current_screen()->id; | |
} | |
} | |
( new WPUserProfilesCMB2() )->add_hooks(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment