Created
December 30, 2018 14:20
-
-
Save Miri92/47db7256c08ec113ca1ce905cb7aea99 to your computer and use it in GitHub Desktop.
Wordpress - Custom meta box with checkbox field
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
function slider_get_meta( $value ) { | |
global $post; | |
$field = get_post_meta( $post->ID, $value, true ); | |
if ( ! empty( $field ) ) { | |
return is_array( $field ) ? stripslashes_deep( $field ) : stripslashes( wp_kses_decode_entities( $field ) ); | |
} else { | |
return false; | |
} | |
} | |
//creating meta box | |
function slider_add_meta_box() { | |
add_meta_box( | |
'memory_meta', //id | |
__( 'Əlavə sahələr', 'custom_meta_fields' ), //title | |
'slider_html', // callback | |
'', // screen - The screen or screens on which to show the box (such as a post type, 'link', or 'comment'). | |
'normal', // context - The context within the screen where the boxes should display. | |
'default' // priority - The priority within the context where the boxes should show ('high', 'low'). | |
); | |
} | |
add_action( 'add_meta_boxes', 'slider_add_meta_box' ); | |
//callback function | |
function slider_html( $post) { | |
wp_nonce_field( '_slider_nonce', 'slider_nonce' ); ?> | |
<p> | |
<input type="checkbox" name="slider" id="slider" value="yes" <?php echo slider_get_meta( 'slider' ) == 'yes'? 'checked':''; ?>> | |
<label for="slider"><?php _e( 'Display on slider', 'slider' ); ?></label> | |
</p> | |
<?php | |
} | |
// saving | |
function slider_save( $post_id ) { | |
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; | |
if ( ! isset( $_POST['slider_nonce'] ) || ! wp_verify_nonce( $_POST['slider_nonce'], '_slider_nonce' ) ) return; | |
if ( ! current_user_can( 'edit_post', $post_id ) ) return; | |
update_post_meta( $post_id, 'slider', $_POST['slider'] ); | |
} | |
add_action( 'save_post', 'slider_save' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment