I wan't to remove the invisible line and paragraph separator from the input when the user creates or edit a post. But it seems to be very inefficient. Is there other way to do this without that many DB operations?
I came with this solution adapting several examples on the internet. I added this code in functions.php:
// Add custom validation to clean the post fields.
// Originally used to remove \u2028 and \u2029 from the contents.
//----------------------------------------
function post_custom_validation ($post_id) {
//check post
if ( $post_id == null || empty($_POST) )
return;
if ( wp_is_post_revision( $post_id ) )
$post_id = wp_is_post_revision( $post_id );
global $post;
if ( empty( $post ) )
$post = get_post($post_id);
global $wpdb;
// remove \u2028 and \u2029 characters.
// From post table
$content = preg_replace('/[\p{Zp}\p{Zl}]+/u','',$post->post_content);
$title = preg_replace('/[\p{Zp}\p{Zl}]+/u','',$post->post_title);
$excerpt = preg_replace('/[\p{Zp}\p{Zl}]+/u','',$post->post_excerpt);
//update DB
$where = array( 'ID' => $post_id );
$wpdb->update( $wpdb->posts, array( 'post_content' => $content, 'post_title' => $title , 'post_excerpt' => $excerpt ), $where );
// From postmeta table
$lead = preg_replace('/[\p{Zp}\p{Zl}]+/u','',get_post_meta($post->ID, 'wm_lead', true));
$subheader = preg_replace('/[\p{Zp}\p{Zl}]+/u','',get_post_meta($post->ID, 'wm_subheader', true));
$footer = preg_replace('/[\p{Zp}\p{Zl}]+/u','',get_post_meta($post->ID, 'wm_footer', true));
//update DB
$where = array( 'ID' => $post_id , 'meta_key' => 'wm_lead');
$wpdb->update( $wpdb->wp_postmeta, array( 'meta_value' => $lead), $where );
$where = array( 'ID' => $post_id , 'meta_key' => 'wm_subheader');
$wpdb->update( $wpdb->wp_postmeta, array( 'meta_value' => $subheader), $where );
$where = array( 'ID' => $post_id , 'meta_key' => 'wm_footer');
$wpdb->update( $wpdb->wp_postmeta, array( 'meta_value' => $footer), $where );
}
add_action('save_post', 'post_custom_validation', 12 );
Aucun commentaire:
Enregistrer un commentaire