Can I edit the wp_post > post_content right before its inserted/updated?

I would need to apply some sort of encryption on whatever gets inserted in the wp_post > post_content, so I was wondering if there is a way, either modifying the core (rather not), or using some filter or hook and function, where I could perform the encryption right before the content gets saved.

And then once called for by the frontend or backend, to apply an decryption, before the post_content gets actually used.

Thanks in advance to anyone with some advice on the matter!

1 Answer
1

OK, this is possible, but it will be a little bit tricky and I would recommend a lot of testing after deploying this solution.

Disclaimer: I use base64_encode and base64_decode as cipher/decipher functions, but of course you can change them to whatever you like.

First part (encoding before post is stored in DB) is pretty easy:

function encrypt_post_content( $data, $postarr ) {
    $data['post_content'] = base64_encode( $data['post_content'] );
    return $data;
}
add_filter( 'wp_insert_post_data', 'encrypt_post_content', 10, 2 );

Second part is a little bit trickier, because WordPress uses raw context in many places and if this context is used, then no filters are applied to post fields…

function decrypt_post_content( $content, $default_editor =false ) {
    return base64_decode( $content );
}
add_filter( 'the_editor_content', 'decrypt_post_content', 10, 2 );
add_filter( 'the_content', 'decrypt_post_content', 1, 1 );

PS. It’s a little bit sad that there is no easy possibility to modify post_content just after getting it from DB… 🙁

Leave a Comment