[wordpress]記事投稿時に文字列を置換させる方法
記事投稿時に強制的に文字列を置換させる方法は以下の通り
ワーカーさんに文章をお願いして作成した文章が「です・ます」調で、「だ」調に変換したいけど、1個1個修正するのがめんどくさい時に使える。
function.phpに以下のコードを追加
/** * 投稿時にコンテンツを自動修正 */ add_filter( 'wp_insert_post_data' , 'replace_post_data' , '99', 2 ); function replace_post_data($data, $postarr){ $search[] = 'なります。'; $replace[] = 'なる。'; $search[] = 'します。'; $replace[] = 'する。'; $search[] = 'ます。'; $replace[] = 'る。'; $search[] = 'です。'; $replace[] = '。'; $modified = str_replace($search,$replace,$data[‘post_content’]); $data['post_content'] = $modified; return $data; }
wp_insert_post_dataにフックさせる関数を作成すればよく、受け取ったデータのpost_contentを変更すればOK
ですます調を効率よく変換したかったので、str_replaceの配列による置換を行っている。
post_content以外のパラメータも変更できる。その他のパラメータはReference/wp insert post dataを参考のこと。
投稿時に自動的に不要なタグを除去する
またpost_content内の不要なHTMLタグを除去したい場合は以下の通り「wp_kses」を使用すると必要なタグだけ残せる。
<?php /** * 投稿時に不要なタグを除去 */ add_filter( 'wp_insert_post_data' , 'replace_post_data' , '99', 2 ); function replace_post_data($data, $postarr){ // 許可するタグ $param = array( 'a' => array( // 属性も残す場合は指定が必要 'href' => array(), ), 'h2' => array(), 'h3' => array(), 'br' => array(), ); $modified = wp_kses($data['post_content'], $param); $data['post_content'] = $modified; return $data; }
$modified = str_replace($search,$replace,$modified);
ここは
$modified = str_replace($search,$replace,$data[‘post_content’]);
ですかね。
なるほど!ありがとうございます!
早速修正しました