インデックスされたエントリに余分なデータを追加する
インデックス対象となるコンテンツは、作業中のエントリの編集画面で表示/編集可能であることが多いですが、SearchWPがインデックスを作成する際にエントリに余分なデータを追加して、そのデータも検索可能にしたい場合もあります。
SearchWPのいくつかのフックを使用して、SearchWPのインデクサーが実行される際に、エントリコンテンツと一緒に任意のデータを含めることができます。
All hooks should be added to your custom SearchWP Customizations Plugin.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // @link https://searchwp.com/documentation/knowledge-base/adding-extra-data-to-indexed-entries/ | |
| // Adding extra data to indexed entries in SearchWP. | |
| add_filter( 'searchwp\entry\data', function( $data, \SearchWP\Entry $entry ) { | |
| $my_extra_meta_key = 'my_extra_meta'; | |
| // SearchWP can index any data type, array/object values will all be processed. | |
| // For this example we will use a string: | |
| $my_extra_meta = 'This content will be searchable!'; | |
| // Store custom Custom Field along existing postmeta. | |
| $data['meta'][ $my_extra_meta_key ] = $my_extra_meta; | |
| return $data; | |
| }, 20, 2 ); | |
| // Add 'extra' meta as available option for your Source Attributes. | |
| add_filter( 'searchwp\source\attribute\options', function( $keys, $args ) { | |
| if ( $args['attribute'] !== 'meta' ) { | |
| return $keys; | |
| } | |
| // This key is the same as the one used in the searchwp\entry\data hook above, they must be the same. | |
| $my_extra_meta_key = 'my_extra_meta'; | |
| // Add "Extra Meta" Option if it does not exist already. | |
| if ( ! in_array( | |
| $my_extra_meta_key, | |
| array_map( function( $option ) { return $option->get_value(); }, $keys ) | |
| ) ) { | |
| $keys[] = new \SearchWP\Option( $my_extra_meta_key, 'Extra Meta' ); | |
| } | |
| return $keys; | |
| }, 20, 2 ); |
これらのフックをSearchWPカスタマイズプラグインに追加すると、上記のコードスニペットで作成したカスタムオプション名に一致するため、extraで検索すると「Extra Meta」カスタムフィールドが表示されます。


