0

I am working on a plugin that has a piece of meta data attached to each post. The fields are editable in a meta box on the post. This is all working fine.

I would like to prevent anyone from modifying the settings in meta box once the post has been published. By virtue of the application looking for this meta data, it doesn't make any sense for the meta data to change after publish.

So, is there any way to tell if a post has been published at least once? This way I can disable the controls in the meta box.

1
  • I think you can only check if the post is published at the moment. To check if it was ever published you'd most likely need to add another meta key and value to store the status once it's published for the first time. Nov 26 '16 at 3:48
1

We can do this by storing the value into postmeta when post is published first time.

function save_ispublished( $post_id ) {

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
        return;

    $published_once = get_post_meta( $post_id, 'is_published', true );

    // Check if 'is_published' meta value is empty.
    if ( ! empty( $published_once ) ) {

        $published_once = 'yes';
    }

    // store is_published value when first time published.
    update_post_meta( $post_id, 'is_published', $published_once );
}
add_action( 'save_post', 'save_ispublished' );

you can check it by get the meta value.

$is_published = get_post_meta( $post_id, 'is_published', true );

if( $is_published == 'yes' ) {

    /*
    * Actions if post is already published atleast once.
    */
}

Hope this help !

1
  • Thanks! This is the way I started solving this after posting the question. The only remaining issue (for me anyway) is back-solving for posts published before the plugin was installed. I'm using a register_activiation_hook for the plugin for that, along with a loop on the output of get_posts(array('post_status' => 'publish')).
    – cstays
    Nov 26 '16 at 14:25
0

I totally agree with @Govind Kumar except for the action uses in the example, you can use publish_post action instead of save_post.

publish_post is an action triggered whenever a post is published, or if it is edited and the status is changed to publish. Save_post will trigger each time the post is save.

publish_post action

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.