Adding default custom fields on new posts in WordPress

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>

8 thoughts on “Adding default custom fields on new posts in WordPress

  1. Props, really good! Thanks, man!
    I was looking for some easier short content management…
    Never thought of custom fiels! :)

  2. I might have missed it in your post, but where do I add this code? I’m desperately looking for a solution to set default Custom Fields for each new posts and this sounds like the perfect solution.

  3. Found the answer by myself: http://www.wpbeginner.com/wp-tutorials/how-to-add-custom-fields-automatically-on-post-publish-in-wordpress/

    add_action(‘publish_page’, ‘add_custom_field_automatically’);
    add_action(‘publish_post’, ‘add_custom_field_automatically’);
    function add_custom_field_automatically($post_id) {
    global $wpdb;
    if(!wp_is_post_revision($post_id)) {
    add_post_meta($post_id, ‘field-name’, ‘custom value’, true);
    }
    }

    Hope that helps others as well ;)

  4. Great stuff!! here is my quastion though….

    Is there any way to get the thumbnail url from uploaded images in post to automaticly be included in the value? If there is no image uploaded in the post then the value an be empty

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>