Created
April 19, 2012 10:18
-
-
Save trovster/2420114 to your computer and use it in GitHub Desktop.
My general checkbox meta box for the WordPress admin area. All custom fields prefix with custom_ are saved automatically with my update function.
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 | |
function post_type_custom_fields_general_featured() { | |
global $post; | |
$custom = get_post_custom($post->ID); | |
$is_featured = is_custom_boolean($custom, 'custom_is_featured'); | |
echo '<p class="checkbox" style="padding-top: 5px;">'; | |
echo '<input type="hidden" name="custom_is_featured" value="false" />'; | |
echo '<input style="margin-right: 5px;" id="custom_is_featured" value="true" type="checkbox" name="custom_is_featured"' . (($is_featured) ? ' checked="checked"' : '') . ' />'; | |
echo '<label for="custom_is_featured" style="font-weight: bold;">Set as Featured?</label>'; | |
echo '</p>'; | |
} | |
function is_custom_boolean($custom, $key) { | |
if(!empty($custom[$key][0]) && $custom[$key][0] === 'true') { | |
return true; | |
} | |
return false; | |
} |
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 | |
function post_type_custom_fields_update($post_id) { | |
global $post; | |
// check user permissions / capabilities | |
if($_POST['post_type'] == 'page') { | |
if(!current_user_can('edit_page', $post_id)) { | |
return $post_id; | |
} | |
} | |
else { | |
if(!current_user_can('edit_post', $post_id)) { | |
return $post_id; | |
} | |
} | |
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { | |
return $post_id; | |
}; | |
// authentication passed, save data | |
// cycle through each posted meta item and save | |
// by default only saves custom fields which are prefixed with custom_ | |
foreach($_POST as $key => $value) { | |
if(strpos($key, 'custom_') !== false) { | |
$current_data = get_post_meta($post_id, $key, true); | |
$new_data = !empty($_POST[$key]) ? $_POST[$key] : null; | |
if(is_null($new_data)) { | |
delete_post_meta($post_id, $key); | |
} | |
else { | |
// add_post_meta is called if not already set | |
// @see http://codex.wordpress.org/Function_Reference/update_post_meta | |
if(strpos($key, 'custom_date_') !== false) { | |
$new_data = strtotime($new_data); // convert to timestamp | |
} | |
update_post_meta($post_id, $key, $new_data, $current_data); | |
} | |
} | |
} | |
return $post_id; | |
} | |
add_action('save_post', 'post_type_custom_fields_update'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment