How to add WordPress Custom Fields to my post types?
Did you ever want to add some WordPress custom fields or specific options to all post types in your WordPress site? That tutorial will show you a quick and easy way to do it.
Open your functions.php
First let us put the following function inside our functions.php
<?php add_action( 'admin_init', 'dt_custom_fields' ); function dt_custom_fields() { $post_types = get_post_types( array('public' => true,'exclude_from_search' => false) ); foreach($post_types as $post_type) { add_meta_box( 'dt-custom-fields', 'My Custom Fields', 'dt_custom_metabox', $post_type, 'normal', 'high' ); } } ?>
The function above simply adds a custom metabox that will contain our WordPress custom fields to all our post types. Next, we need to write the dt_custom_metabox() function which should control the display of fields in our post editing page.
Writing the dt_custom_metabox() function
<?php function dt_custom_metabox(){ global $post; $postmeta = get_post_custom($post->ID); $custom_field = $postmeta["custom_field"][0]; ?> <p><label for="custom_field">Custom Field:</label></p> <p><input type="text" name="custom_field" id="custom_field" value="<?php echo $custom_field; ?>" class="large-text" /></p> <?php } ?>
The above code shows a very basic example of adding WordPress custom fields in our new metabox. You can add any more as you want. The last and final step is to save our custom fields when the post is updated/published.
Save custom fields!
<?php add_action('save_post', 'dt_save_custom_fields'); function dt_save_custom_fields(){ global $post; update_post_meta($post->ID, "custom_field", esc_url($_POST["custom_field"]) ); } ?>
That’s the last bit of code. We simply update the custom field meta key when the post is updated.
The Complete and Final Code
<?php add_action( 'admin_init', 'dt_custom_fields' ); function dt_custom_fields() { $post_types = get_post_types( array('public' => true,'exclude_from_search' => false) ); foreach($post_types as $post_type) { add_meta_box( 'dt-custom-fields', 'My Custom Fields', 'dt_custom_metabox', $post_type, 'normal', 'high' ); } } function dt_custom_metabox(){ global $post; $postmeta = get_post_custom($post->ID); $custom_field = $postmeta["custom_field"][0]; ?> <p><label for="custom_field">Custom Field:</label></p> <p><input type="text" name="custom_field" id="custom_field" value="<?php echo $custom_field; ?>" class="large-text" /></p> <?php } add_action('save_post', 'dt_save_custom_fields'); function dt_save_custom_fields(){ global $post; update_post_meta($post->ID, "custom_field", esc_url($_POST["custom_field"]) ); } ?>
That’s it you’ve now added custom fields to all post types. This example was very little example and tutorial on how to build custom fields within custom metaboxes for your WordPress post types simply and easily. I hope you’ve found it useful and interesting.
The post Adding WordPress Custom Fields to All Post Types appeared first on Deluxe Themes.