How to Add custom fields automatically for each new section / page in WordPress

Custom fields allow you to add additional metadata in your different content (pages, articles or custom content types). These very powerful fields can be created automatically for each new article or other content. Just you will have to enter the corresponding values for metadata.

Recall at first, that a custom field consists of a key (the field name) and one or more values are used for creating a custom field for each of the new content.

To automate their creations, just add these lines of code in the functions.php file located in /wp-content/themes/Name_THEME/ or go through the back office via WordPress Editor Appearance menu. This second method is more risky in case of errors:

add_action (‘wp_insert_post’, ‘wpc_champs_personnalises_defaut’);
wpc_champs_personnalises_defaut function ($ post_id)
if ($ _GET [‘post_type’]! = ‘page’) {
add_post_meta ($ post_id, ‘custom_field_1’,”, true);
add_post_meta ($ post_id, ‘custom_field_2’,”, true);
return true;

More information to know about this snippet:

if ( $_GET[‘post_type’] != ‘page’ ) { : you can choose the content type for which the fields will be generated. For the example, all the pages – note the presence of the exclamation point. You can use the value for items post slug or any custom post types – or not using the exclamation point to manage exclusions;
add_post_meta($post_id, ‘custom_field_1’, ”, true); : Here are two example lines creating custom fields. Here, two fields entitled custom_field_1 and custom_field_2 will be generated. So feel free to add as many lines as desired with the names of your choice. Also note that the third argument can be set to indicate a predefined value like this: add_post_meta($post_id, ‘custom_field_1’, ‘my_value_default’, true);

Many plugins are already using this technique to insert metadata which will then be displayed on the site or keep stored in the database.

Leave a Reply

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