Search Regex による Markdown 記法の一括置換

Jetpack プラグインの Markdown 機能による Markdown 記法を、Search Regex プラグインでは一括置換することができません。

これは、Markdown 記法による編集データが、通常の投稿とは異なる場所に保存されているためです。具体的には、編集データは投稿テーブルの post_content_filtered フィールドに格納され、通常の投稿が格納される post_content フィールドには、変換後の HTML が格納されるためです。

そこでここでは、Search Regex プラグインを、post_content_filtered フィールドに対応させる方法を紹介します。

post_content_filtered.php

下記の PHP コードを、ファイル名「post_content_filtered.php」として作成します。

<?php

class SearchPostContentFiltered extends Search {
	function find( $pattern, $limit, $offset, $orderby ) {
		global $wpdb;

		$sql = "SELECT ID, post_content_filtered, post_title FROM {$wpdb->posts} WHERE post_status != 'inherit' AND post_type IN ('post','page') ORDER BY ID " . $orderby;

		if ( $limit > 0 ) {
			$sql .= $wpdb->prepare( " LIMIT %d,%d", $offset, $limit );
		}
		$results = array();
		$posts = $wpdb->get_results( $sql );

		if ( count( $posts ) > 0 ) {
			foreach ( $posts as $post ) {
				if ( ( $matches = $this->matches( $pattern, $post->post_content_filtered, $post->ID ) ) ) {
					foreach ( $matches AS $match ) {
						$match->title = $post->post_title;
					}
					$results = array_merge( $results, $matches );
				}
			}
		}

		return $results;
	}

	function get_options( $result ) {
		$options[] = '<a href="'.get_permalink ($result->id).'">' . __( 'view', 'search-regex' ) . '</a>';

		if ( current_user_can( 'edit_post', $result->id ) ) {
			$options[] = '<a href="' . get_bloginfo ( 'wpurl' ) . '/wp-admin/post.php?action=edit&amp;post=' . $result->id . '">' . __( 'edit', 'search-regex' ) . '</a>';
		}
		return $options;
	}

	function show( $result ) {
		printf( __( 'Post #%d: %s', 'search-regex' ), $result->id, $result->title );
	}

	function name () {
		return __( 'Post content filtered', 'search-regex' );
	}

	function get_content( $id ) {
		global $wpdb;

		$post = $wpdb->get_row( $wpdb->prepare( "SELECT post_content_filtered FROM {$wpdb->prefix}posts WHERE id=%d", $id ) );
		return $post->post_content_filtered;
	}

	function replace_content( $id, $content ) {
		global $wpdb;
		$wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->posts} SET post_content_filtered=%s WHERE ID=%d", $content, $id ) );
	}
}

※ このコードのライセンスは、Search Regex と同じ GPLv3 とします。

作成した PHP ファイルを、Search Regex プラグインが格納されているフォルダー下の searches フォルダーに配置します。

Search Regex

Search Regex ページの、「Source」に「Post content filtered」が追加されます。

この、「Post content filtered」を選択することで、編集データを置換することができます。なお、これだけでは変換後の HTML は置換されないので、Markdown 記法に対応するように、 変換後の HTML である「Post content」も置換することになると思います。

重要事項

Jetpack の Markdown が、どのような処理でどのように格納されているかなどは、正式なドキュメントに記載が見当たらず、プラグインのコードを解析したものであり、正規の方法ではありません。この方法を使用する場合は、処理を理解した上で自己責任において行ってください。

対象バージョン: WordPress 5.0.3、Search Regex 1.4.16、Jetpack by WordPress.com 6.9

コメントを残す

メールアドレスが公開されることはありません。

日本語でコメントを入力してください。(スパム対策)