Thord Daniel Hedengren - Smashing WordPress_ Beyond the Blog-Wiley (2014)

(avery) #1

200 PART III • Using Plugins with WordPress


Next, create the actual meta box, with the necessary labels and fields so that the user will
know what to do:

// The meta box
function addaff_meta_box( $post ) {

// Get values for filling in the inputs if you have them.
$title = get_post_meta( $post->ID, '_addaff_meta_box_title', true );
$url = get_post_meta( $post->ID, '_addaff_meta_box_url', true );

// Nonce to verify intention later
wp_nonce_field( 'save_addaff_meta_box', 'addaff_meta_box_nonce' );
?>
<p>
<?php _e( 'The link title will be linked and appended to the bottom of
every post when the full content is shown. This might include archive
pages, depending on your theme. You can alter the particulars on
<a href="options-general.php?page=addaff">the AddAff settings page</a>.',
'adaff' ); ?>
</p>
<p>
<label for="event-title"><strong><?php _e( 'Affiliate Link Title:',
'addaff' ); ?></strong></label>
<input type="text" class="widefat" id="event-title"
name="_addaff_meta_box_title" value="<?php echo $title; ?>" />
</p>
<p>
<label for="event-title"><strong><?php _e( 'Affiliate Link Title:',
</strong></label>
<input type="text" class="widefat code" id="event-url"
name="_addaff_meta_box_url" value="<?php echo $url; ?>" />
</p>

<?php
}

The meta data filled out in these boxes ends up in _addaff_meta_box_title and
_addaff_meta_box_url, which is what you’ll call with get_post_meta() when it is
time to output the title and product link.

Finally, you need to save the date when the post is updated:

// Save stuff
add_action( 'save_post', 'addaff_meta_save' );
function addaff_meta_save( $id ) {

if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

if ( !isset( $_POST['addaff_meta_box_nonce'] ) ||
!wp_verify_nonce( $_POST['addaff_meta_box_nonce'], 'save_addaff_meta_box' ) )
return;
Free download pdf