Are you looking for a way to add a custom field to a post or page when it is published? This snippet will add a custom field, with a name and value of your choice, to a post or page when it is published.
Instructions:
- Add this code to your theme’s functions.php file or in a site-specific plugin.
- Replace the
FIELD_NAME
text and theCUSTOM VALUE
text to the name and value of your choice.
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); } }
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: 7 Best Drag and Drop WordPress Page Builders Compared.
Nice! And I guess we can use published_to_post hook to change that value. Or even better:
function post_unpublished( $new_status, $old_status, $post ) {
if ( $old_status == 'publish' && $new_status != 'publish' ) {
// Post is unpublished
}
}
add_action( 'transition_post_status', 'post_unpublished', 10, 3 );
Any better way to do it?