How To Add a Custom Field via WordPress plugin?

Sometimes we need to add custom data for our posts and pages other than title and content. Suppose you are using Custom Post Types for your book store and want to save the Book price as well. You have added title and description but for price you will add a custom field. Today, you will learn that how you can add custom fields via WordPress plugins. In modern WordPress development, these kinds of functional stuff should be done via plugins instead of coding in WordPress themes.

Before moving forward please download the plugin from here. Please open the class file “class_custom_field.php”.

I will explain every code snippet step by step.

The above function is simply getting instance of class and returning it.

This code snippet is saying that when a post is to be edited or a new post is to be made get instance of “customField” class and getting an instance is of course meant to initialize and render the text field in the post page.

“load-post” and “load-post-new” are two new hooks.

 

Class constructor is adding functions to the hooks for rendering and saving the data.

 

The “add_meta_box” is in fact the responsible to render the text field. First argument is setting “id”, second argument is setting title, third argument is giving the definition that how will it be and fourth argument is setting the screen is it a “page” or a “post” where this custom field will be rendered on.

 

Inside “save” function first we are checking whether “nonce” is set. “nonce” is put in the form for the security reasons. You can read about it from here. Then we are verifying whether it is a valid “nonce”. Then simply checking whether the current user is authorized to perform this action. Then we are sanitizing the data and saving or updating the data using “update_post_meta” giving a key. Because with this key we will later retrieve our data.

 

Inside “render_meta_box_content” we are generating “nonce”. Then getting the data if it was set using “get_post_meta” function and putting this value in the text field and rendering the text field.

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *