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

(avery) #1

CHAPTER 7 • Making the Most of WordPress Plugins 201


if ( !current_user_can( 'edit_post' ) ) return;


if ( isset( $_POST['_addaff_meta_box_title'] ) )
update_post_meta( $id, '_addaff_meta_box_title',
esc_attr( strip_tags( $_POST['_addaff_meta_box_title'] ) ) );


if ( isset( $_POST['_addaff_meta_box_url'] ) )
update_post_meta( $id, '_addaff_meta_box_url',
esc_attr( strip_tags( $_POST['_addaff_meta_box_url'] ) ) );


}


You’re hooking on to save_post with the addaff_meta_save() function. The content is
escaped to make sure that there’s no funky stuff getting through. It wouldn’t do to have
custom HTML and whatnot here because you want to have complete control over that when
outputting the affiliate link. Finally, update_post_meta() is used to actually save the data,
which happens whenever the save_post action occurs. This includes autosaves. Figure 7-7
shows how the finished meta box looks on the Edit Post screen.


Figure 7-7: The Affiliate Product Link box on the Edit Post screen.


FILTERING THE_CONTENT


You’re almost there. The only thing that remains is to output the result under the posts. You’ll do
this with the help of add_filter() and the the_content hook. This comes with a few
caveats, as there are a lot of plugins that want to insert stuff after the content, so keep this in mind.


Start with the filter because that’s the easy part:


/ OUTPUT AFFILIATE LINK
Add the affiliate link after the_content()
/


add_filter( 'the_content', 'addaff_link', 11 );


The addaff_link() function is passed to the_content with add_filter() — no
biggie, right? Now take a look at the actual function:


function addaff_link( $content ) {


// Store _addaff_meta_box_title in $addaff_link_title
$addaff_link_title = get_post_meta( get_the_ID(), '_addaff_meta_box_title',
true );

Free download pdf