Created
August 14, 2022 14:19
-
-
Save ahmedch1/74d4ba18fb8209c263e9a9aa410444a1 to your computer and use it in GitHub Desktop.
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 | |
// Add FieldName MetaBox | |
abstract class FieldName_Meta_Box { | |
/** | |
* Set up and add the meta box. | |
*/ | |
public static function add() { | |
$screens = [ 'posttypename' ]; | |
foreach ( $screens as $screen ) { | |
add_meta_box( | |
'fieldname_id', // Unique ID | |
'Field Name', // Box title | |
[ self::class, 'html' ], // Content callback, must be of type callable | |
$screen // Post type | |
); | |
} | |
} | |
/** | |
* Save the meta box selections. | |
* | |
* @param int $post_id The post ID. | |
*/ | |
public static function save( int $post_id ) { | |
if ( array_key_exists( 'fieldname_field', $_POST ) ) { | |
update_post_meta( | |
$post_id, | |
'fieldname_meta_key', | |
$_POST['fieldname_field'] | |
); | |
} | |
} | |
/** | |
* Display the meta box HTML to the user. | |
* | |
* @param \WP_Post $post Post object. | |
*/ | |
public static function html( $post ) { | |
$value = get_post_meta( $post->ID, 'fieldname_meta_key', true ); | |
?> | |
<label for="fieldname_field">Description for this field</label> | |
<select name="fieldname_field" id="fieldname_field" class="postbox"> | |
<option value="">Select Location</option> | |
<option value="tunis" <?php selected( $value, 'something' ); ?>>Tunis</option> | |
<option value="sousse" <?php selected( $value, 'else' ); ?>>Sousse</option> | |
</select> | |
<?php | |
} | |
} | |
add_action( 'add_meta_boxes', [ 'FieldName_Meta_Box', 'add' ] ); | |
add_action( 'save_post', [ 'FieldName_Meta_Box', 'save' ] ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment