How it works...

WordPress' custom fields section is a built-in feature for storing key-value pairs in the wp_postmeta table. The custom fields section is not enabled by default in the new Gutenberg editor. We used the Options menu item on More tools and options menu to enable the custom fields section. Once enabled, the book creation/edit screen will show a new section for creating custom fields under the content editor. 

We can either add a value to an existing meta key or use a new meta key for the field. In this case, we clicked the Enter New link and added a new meta key and value for the book.  We used the Add Custom field button to add multiple meta keys and values for the book. Once the Update/Publish button is clicked, these meta details will be automatically saved in the wp_postmeta table as a meta key and value. We can use this feature to add basic custom data for books when an administrative user is adding the details.

This feature can be used by any user with book editing permission. However, it's not very user-friendly to add a meta key and value manually and directly into the field. If we needed an additional image for the book, we have to add the URL of the image as the value. As a solution, we can add custom fields with custom designs and different field types using meta boxes. These fields allow a user to upload files, select values, select dates, and tick the available options instead of just typing the values directly.

In this recipe, we used the meta box to add two fields called Book Pages and Book Price. The process and how it works is similar to the one we discussed in Chapter 6, Setting up a Blogging and Editorial Workflow in the Creating private posts for specific users recipe. Therefore, we are only going to look at the differences in the book custom field saving process compared to the code we used in that recipe.

In the save_post action, we call the wpccp_chapter7_save_post_restrictions function. Inside the function, we use the following conditional check:

if(isset($post->post_type) && $post->post_type != 'book'){
return;
}

This code checks for the book post type and only executes the code for books. By default, the save_post action will be executed for all the post types. In Chapter 6, Setting up a Blogging and Editorial Workflow we didn't use this conditional check as we wanted the user restriction feature on all post types. In this case, book fields are only applicable to books, so we used a conditional check to avoid executing the code for other post types. Now, the book custom fields will be stored in the wp_postmeta table with their respective keys. We can use this technique to build any kind of custom field based on post type.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.72.74