Home / custom field / Add custom field automatically when post or page is publish
  • How to Add custom field automatically when post or page is publish

    add-custom-field-and-value-automatically-on-post-page-publish

    Adding this snippet to the functions.php of your wordpress theme will add a custom field to a post or page when published. Don’t forget to update the FIELD_NAME and the CUSTOM VALUE.

    ( click code to copy )

    wordpress snippet : PHP

    <>
    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);
        }
    }
    

    ( WordPress codex functions, hooks, in this snippet. )

    publish_post, is_post, add_post_meta, wp_is_post_revision, add_action, _n, wp,
  • 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?