Custom fields are essential part of every WordPress site. You know how to add it – Enter new – [type some name] – [type some content] – Add custom field. It’s not complicated process, but it is not as simple as it could be, especially if all of your posts need to have same custom fields, for example, price, size or some very general values. If it is your case, use this snippet and make your life easier.
<pre>add_action('wp_insert_post', 'mk_set_default_custom_fields');
function mk_set_default_custom_fields($post_id)
{
if ( $_GET['post_type'] != 'page' ) {
add_post_meta($post_id, 'price', '', true);
add_post_meta($post_id, 'link', '', true);
}
return true;
}</pre>
Simple, right?
You can put numerous custom fields or put just one. It’s up to you.
Oh, I forgot. This adds an empty custom field (with no value). For adding custom field with some value addÂ
<pre>add_post_meta($post_id, 'custom field name', 'custom field value', true);</pre>