Last active
February 6, 2019 21:21
-
-
Save amanhstu/8974c0041a211d2a3769522aa15ddac6 to your computer and use it in GitHub Desktop.
Creating a meta box in wordpress post and showing that value in your theme file
This file contains hidden or 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 | |
// Sub Title Metabox | |
/** | |
* function to return a custom field value. | |
*/ | |
function wpshed_get_custom_field( $value ) { | |
global $post; | |
$custom_field = get_post_meta( $post->ID, $value, true ); | |
if ( !empty( $custom_field ) ) | |
return is_array( $custom_field ) ? stripslashes_deep( $custom_field ) : stripslashes( wp_kses_decode_entities( $custom_field ) ); | |
return false; | |
} | |
/** | |
* Register the Meta box | |
*/ | |
function wpshed_add_custom_meta_box() { | |
add_meta_box( 'wpshed-meta-box', __( 'CSDug Subtitle', 'wpshed' ), 'wpshed_meta_box_output', 'post', 'normal', 'high' ); | |
} | |
add_action( 'add_meta_boxes', 'wpshed_add_custom_meta_box' ); | |
/** | |
* Output the Meta box | |
*/ | |
function wpshed_meta_box_output( $post ) { | |
// create a nonce field | |
wp_nonce_field( 'my_wpshed_meta_box_nonce', 'wpshed_meta_box_nonce' ); ?> | |
<p> | |
<label for="wpshed_textfield"><?php _e( 'Subtitle', 'wpshed' ); ?>:</label> | |
<input type="text" name="wpshed_textfield" id="wpshed_textfield" value="<?php echo wpshed_get_custom_field( 'wpshed_textfield' ); ?>" size="50" /> | |
</p> | |
<?php | |
} | |
/** | |
* Save the Meta box values | |
*/ | |
function wpshed_meta_box_save( $post_id ) { | |
// Stop the script when doing autosave | |
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; | |
// Verify the nonce. If insn't there, stop the script | |
if( !isset( $_POST['wpshed_meta_box_nonce'] ) || !wp_verify_nonce( $_POST['wpshed_meta_box_nonce'], 'my_wpshed_meta_box_nonce' ) ) return; | |
// Stop the script if the user does not have edit permissions | |
if( !current_user_can( 'edit_post', get_the_id() ) ) return; | |
// Save the textfield | |
if( isset( $_POST['wpshed_textfield'] ) ) | |
update_post_meta( $post_id, 'wpshed_textfield', esc_attr( $_POST['wpshed_textfield'] ) ); | |
} | |
add_action( 'save_post', 'wpshed_meta_box_save' ); | |
?> | |
<?php | |
// Put this code in your theme where you want to echo or output the meta box value that is putted in the post | |
global $post; echo get_post_meta($post->ID,'wpshed_textfield',true); | |
?> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment