Skip to content

Instantly share code, notes, and snippets.

@zviryatko
Created June 16, 2016 09:27
Show Gist options
  • Save zviryatko/207fb269bc045a9b058110f981f109e2 to your computer and use it in GitHub Desktop.
Save zviryatko/207fb269bc045a9b058110f981f109e2 to your computer and use it in GitHub Desktop.
Wordpress custom fields.
<?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='text' id='<?php echo $field_id; ?>' name='<?php echo $field_id; ?>' value='<?php echo esc_attr($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 (isset($_POST[$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)) : ?>
* <p><?php echo $post->$field_id; ?></p>
* <?php endif;
* endforeach; ?>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment