Created
March 26, 2021 21:46
-
-
Save chrispian/3891822dca4bafe0e8babd548e030231 to your computer and use it in GitHub Desktop.
Create WordPress metaboxes OOP style
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 | |
/** | |
* Plugin Name: CHB Meta Box test | |
* Plugin URI: http://www.chrispian.com | |
* Description: Just testing out OOP Meta Boxes. | |
* Version: 0.0.1 | |
* Requires at least: 5.3 | |
* Requires PHP: 7.2 | |
* Author: Chrispian H. Burks | |
* Author URI: http://chrispian.com | |
* License: GPL v2 or later | |
* License URI: https://www.gnu.org/licenses/gpl-2.0.html | |
* Text Domain: chb-meta-box-test | |
* Domain Path: /languages | |
*/ | |
namespace CHB; | |
/* | |
Reference: https://developer.wordpress.org/plugins/metadata/custom-meta-boxes/ | |
*/ | |
class Meta_Box | |
{ | |
public static function add() { | |
$screens = [ 'post', 'page' ]; | |
foreach ($screens as $screen) { | |
add_meta_box( | |
'test_box_id', // Unique ID | |
'Test Meta Box', // Box title | |
[self::class, 'html'], // Content callback, must be of type callable | |
$screen, // Post type | |
'side' // Varies based on screen. Ex: Screen = post contexts: 'normal', 'side', and 'advanced' | |
); | |
} | |
} | |
public static function save( $post_id ) { | |
if ( array_key_exists( 'chb_test_field', $_POST ) ) { | |
update_post_meta( | |
$post_id, | |
'_chb_test_meta_key', | |
$_POST['chb_test_field'] | |
); | |
} | |
} | |
public static function html( $post ) { | |
$value = get_post_meta( $post->ID, '_chb_test_meta_key', true ); | |
?> | |
<label for="chb_test_field"><strong>Test Option</strong></label> | |
<select name="chb_test_field" id="chb_test_field" class="postbox"> | |
<option value="">Select</option> | |
<option value="Option 1" <?php selected($value, 'Option 1'); ?>>Option 1</option> | |
<option value="Option 2" <?php selected($value, 'Option 2'); ?>>Option 2</option> | |
</select> | |
<?php | |
} | |
} | |
add_action('add_meta_boxes', ['CHB\Meta_Box', 'add']); | |
add_action('save_post', ['CHB\Test_Meta_Box', 'save']); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment