Created
December 28, 2022 10:22
-
-
Save thierrypigot/131eca301157f18b048a425e1d6d04e9 to your computer and use it in GitHub Desktop.
Plugin to add metabox, field to select a date and a shortcode to use this value in my content
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: Metabox Date Select | |
Plugin URI: https://example.com | |
Description: Plugin to add metabox, field to select a date and a shortcode to use this value in my content. | |
Version: 1.0 | |
Author: Your Name | |
Author URI: https://example.com | |
License: GPL2 | |
License URI: https://www.gnu.org/licenses/gpl-2.0.html | |
Text Domain: metabox-date-select | |
*/ | |
// Register meta boxes | |
add_action( 'add_meta_boxes', 'metabox_date_select_register_meta_boxes' ); | |
function metabox_date_select_register_meta_boxes() { | |
add_meta_box( 'metabox_date_select_meta_box', __( 'Date Select', 'metabox-date-select' ), 'metabox_date_select_display_callback', 'post' ); | |
} | |
// Display meta box | |
function metabox_date_select_display_callback( $post ) { | |
wp_nonce_field( basename( __FILE__ ), 'metabox_date_select_nonce' ); | |
$date_value = get_post_meta( $post->ID, '_metabox_date_select', true ); | |
?> | |
<label for="metabox_date_select"><?php _e( 'Pick a date:', 'metabox-date-select' ); ?></label> | |
<input type="date" name="metabox_date_select" id="metabox_date_select" value="<?php echo esc_attr( $date_value ); ?>" /> | |
<?php | |
} | |
// Save meta box | |
add_action( 'save_post', 'metabox_date_select_save_meta_box' ); | |
function metabox_date_select_save_meta_box( $post_id ) { | |
if ( ! isset( $_POST['metabox_date_select_nonce'] ) || ! wp_verify_nonce( $_POST['metabox_date_select_nonce'], basename( __FILE__ ) ) ) | |
return; | |
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) | |
return; | |
if ( ! current_user_can( 'edit_post', $post_id ) ) | |
return; | |
if ( isset( $_REQUEST['metabox_date_select'] ) ) { | |
update_post_meta( $post_id, '_metabox_date_select', sanitize_text_field( $_POST['metabox_date_select'] ) ); | |
} | |
} | |
// Shortcode | |
add_shortcode( 'metabox_date_select', 'metabox_date_select_shortcode' ); | |
function metabox_date_select_shortcode( $atts ) { | |
global $post; | |
$date_value = get_post_meta( $post->ID, '_metabox_date_select', true ); | |
return $date_value; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment