In my last post, I showed you how I created a custom post type for my quote generator. I wanted to add a couple of custom fields to my custom post type. I wanted to add a custom field for the quote author which I will call ‘By’ and a custom field for the source where I found the quote. I wanted to show both fields in a separate meta box on the post.
Here’s how I added the meta box for the two fields:
add_action( 'add_meta_boxes', 'cc_add_byline_box');
function cc_add_byline_box() {
add_meta_box(
'cc_sectionid',
__( 'Info' ),
'cc_inner_custom_box',
'quote',
'normal',
'high'
);
}
function cc_inner_custom_box( $post ) {
$by = get_post_meta($post->ID, 'cc_by',true);
wp_nonce_field( plugin_basename( __FILE__ ), 'cc_noncename');
echo '<label>By:</label><br />
<input id="cc_by" name="cc_by" value="<?php echo $by ?>" style="width:50%;"/>
<br /><br />
<label>Source:</label><br />
<input id="cc_source" name="cc_source" value="<?php echo get_post_meta($post->ID, 'cc_source', true) ?>" style="width:80%;" />
<br />';
}
Then we want to reset the query and add the function to save the information to the quote custom post:
wp_reset_query();
add_action('save_post','cc_save_postdata');
function cc_save_postdata( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
if ( !wp_verify_nonce( $_POST['cc_noncename'], plugin_basename( __FILE__ ) ) )
return;
if ( 'page' == $_POST['post_type'] )
{
if ( !current_user_can( 'edit_page', $post_id ) )
return;
}
else
{
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
$by = $_POST['cc_by'];
$source = $_POST['cc_source'];
update_post_meta($post_id , 'cc_by', $by);
update_post_meta($post_id , 'cc_source', $source);
}
I placed all the code in my quotes.php file in my plugin. I could also put this in my functions.php file.
This gives me this meta box in the quote custom post:
