filter等で文字列置換をする時、str_replace()をやめて、strtr()を使う

WordPressでサイトを運営していると、例えば引っ越しや、SSL化等様々な場面で、URLや文字列の置換をする必要が出ることがあります。

Search Regex — WordPress プラグイン等を使って、一気に書き換えることもできますが、

誤変換してしまうと、バックアップから復元したりといった作業が発生します。

変換の内容が、きっちりと決まるまでの間、フィルターを使って出力時のURLを変更しておいて、しばらく運用しながら様子を見るといった作業をしようとすると

PHPの文字列置換関数の出番がやってきます。最もベーシックで簡単なのは str_replace()ですが、strstrでも置換できるようなので、メモに残します。

strtr()チョットお気に入り

投稿本文の文字列置換の例

functions.php

/**
 * http:をhttpsに変換
 */
add_filter('post_link', 'change_to_https' );
add_filter('wp_nav_menu', 'change_to_https' );
add_filter('wp_get_custom_css', 'change_to_https' );
add_filter('widget_text_content', 'change_to_https' );
add_filter( 'widget_custom_html_content','change_to_https' );
add_filter( 'post_type_archive_link','change_to_https' );
add_filter( 'tag_link','change_to_https' );
add_filter( 'category_link','change_to_https' );
add_filter( 'the_content','change_to_https' );
add_filter('the_content_rss','change_to_https' );
function change_to_https( $content ) {
 
	$replace_pairs= array('http://tenman.info'=>'https://tenman.info',
							'http://www.tenman.info'=>'https://www.tenman.info');
	
	return strtr( $content, $replace_pairs );
}

Raindropsテーマ1.488で上記のようなフィルター機能を使った http:からhttps:への切り替え機能を追加しました。

[emulsion_relate_posts]