Created
June 16, 2016 09:31
-
-
Save zviryatko/47fd07acbadfbaf90bb07ecef43eee00 to your computer and use it in GitHub Desktop.
Wordpress custom fields - checkboxes
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 | |
/** | |
* Added custom metaboxes to post types on admin init action. | |
*/ | |
function dummy_add_metabox() { | |
add_meta_box("metabox-id", "Metabox name", "dummy_metabox_function", "page"); | |
} | |
add_action("admin_init", "dummy_add_metabox"); | |
function dummy_custom_fields() { | |
return array( | |
'field_id1' => __('Field 1','dummy'), | |
'field_id2' => __('Field 2','dummy'), | |
'field_id3' => __('Field 3','dummy'), | |
'field_id4' => __('Field 4','dummy'), | |
); | |
} | |
/** | |
* Custom metabox callback function. | |
*/ | |
function dummy_metabox_function() { | |
global $post; | |
$fields = dummy_custom_fields(); ?> | |
<table> | |
<tbody><?php | |
foreach( $fields as $field_id => $label ) : ?> | |
<tr> | |
<th style='text-align:right;' scope='row'><label for='<?php echo $field_id; ?>'><?php echo $label ?></label></th> | |
<td><input type='checkbox' id='<?php echo $field_id; ?>' name='<?php echo $field_id; ?>' value='1' <?php checked(1, $post->$field_id); ?>></td> | |
</tr> | |
<?php endforeach; ?> | |
</tbody> | |
</table><?php | |
} | |
/** | |
* Save post action callback. | |
*/ | |
function dummy_save_post( $post_id, $post ) { | |
if (!defined('DOING_AUTOSAVE') && !DOING_AUTOSAVE) | |
return $postID; | |
if ( !current_user_can( 'edit_page', $post_id ) ) | |
return; | |
$fields = dummy_custom_fields(); | |
foreach ( array_keys($fields) as $field_id ) { | |
if (!empty($_POST[$field_id])) { | |
if ($_POST[$field_id] != $post->$field_id) { | |
update_post_meta($post_id, $field_id, $_POST[$field_id]); | |
} | |
} | |
else { | |
delete_post_meta($post_id, $field_id ); | |
} | |
} | |
} | |
add_action('save_post', 'dummy_save_post', 10, 2); | |
/** | |
* To show custom field in template use this code: | |
* <?php | |
* $fields = dummy_custom_fields(); | |
* foreach ( $fields as $field_id => $label ) : | |
* if (isset($post->$field_id) && $post->$field_id) : ?> | |
* <p><?php echo $label; ?></p> | |
* <?php endif; | |
* endforeach; ?> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment