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

(avery) #1

CHAPTER 6 • Advanced Theme Usage 143


You can create several meta boxes within this function, but for this example, just create one.
The meta box you’re creating has the ID smashing-post-demo, the title Example Box,
and the callback function (I’ll get to that in a little bit) smashing_post_demo_meta_box,
and it should appear only on posts in admin thanks to post and show up on the right side,
with the default priority. You can read up more on what arguments you can pass to
add_metabox() in the Codex at [http://codex.wordpress.org/Function](http://codex.wordpress.org/Function_)
Reference/add_meta_box.


You need to create another function called smashing_post_demo_meta_box(), used
with the callback in add_meta_box(), to actually create the box:


// Display the demo meta box
function smashing_post_demo_meta_box( $object, $box ) { ?>
<?php wp_nonce_field( basename( FILE ), 'smashing_post_demo_nonce' ); ?>






id="smashing-post-demo" value=" esc_attr( get_post_meta( $object->ID,
'smashing_post_demo', true ) ); ?>" size="30" />


// Function ends, back to business
}

The function includes a nonce field to make sure that any forms within are verified by
WordPress. If you are unfamiliar with nonces, you should read up on them at http://
codex.wordpress.org/Function_Reference/wp_nonce_field.


The rest is simple HTML, which is easier to manage outside of PHP, so that’s why I’m leaving
that for a bit. The input field fetches the value with get_postmeta() and the ID using
$object-
>ID. It is sanitized with esc_attr().


Now you have a meta box on your Add New Post and Edit Post screens! Figure 6-3 shows it in
action.


Figure 6-3: Look at that meta box.

Free download pdf