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>
Props, really good! Thanks, man!
I was looking for some easier short content management…
Never thought of custom fiels!
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.
Could you send to me your email adress? I would like to translate your “Simple comming soon and under construction” in to Polish, and we can cooperate.
Where do I put this code snippet? In single.php? Let me know please! Great tip! Thanks.
No, you should put it into functions.php file.
Any chance to display custom fields when editing a post?
I tried:
add_action(‘edit_post_link’, ‘mk_set_default_custom_fields’);
without success.
Reference: edit_post_link at http://codex.wordpress.org/Function_Reference/edit_post_link
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
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