When building our WPBeginner Gallery site, we required a way to automatically generate custom short URLs for each submitted site and save them as custom fields right upon publication. We'll cover Bit.ly shortlinks in the next guide, but here's how to auto-add custom fields to WordPress posts—a powerful technique for developers extending WordPress beyond blogging.
Open your theme's functions.php file and insert this proven code snippet:
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);
}
}Replace 'field_name' and 'custom_value' with your specific field name and value. This simple, reliable method unlocks advanced WordPress customization.
Source: WPCanyon