Every time an administrator or content manager visits the platform's backend, WordPress creates a number of meta boxes for all of its internal editors (posts, pages, links, and so on) using the add_meta_box function that we have seen in the previous two chapters.
In this recipe, we will use the same add_meta_box function twice to associate a new box to the page and post editors, with both calls registering the same callback function, since we want the same functionality in both places. As WordPress stores posts and pages in the same database table, it will automatically make sure that all the entries have unique IDs between both types of entries.
The other function that we have seen before is get_post_meta, which is used to retrieve custom metadata associated with post entries.
The content of the meta box itself is displayed using standard HTML. As this box will be part of a larger editor, there is no need to worry about declaring a form in this box.
Once the new dialog section is created, the next task is to put code in place to store data from the additional fields upon submission through the use of the save_post action. Functions associated with this hook are called when posts of any type are saved. When executed, the associated function receives two parameters from WordPress that contain the ID of the post being saved and a copy of all the data that has been processed to be saved so far. The callback also has access to all the server post data received from the user, and uses the sanitize_text_field and esc_url functions to make sure that no malicious content was received.
As indicated in the previous chapter, it is important to set the fourth parameter of the add_action call--that is, accepted_args--for actions and filters that receive more than one argument. If it is not specified, these additional arguments will not be available to the receiving hook function.
Working with the assumption that the meta box was only added to the post and page editors, the code contained in the ch5_psl_save_source_data function first checks to see whether the post type is set as a post or page. If it is one of these two types, it moves on to check for the presence of post data for the source name and address fields. If found, update_post_meta is called once for each field to store the new information in the site's database associated with the posts that it belongs to. Making a call to the update_post_meta function actually updates the post custom field data if it exists or creates it in the case of new post or page entries.