sanitize_term_field()


WordPress関数sanitize_term_field()は、タクソノミー用のタームフィールドの値をサニタイズするために使用されます。この関数は、入力値の安全性を確保し、不正なデータが保存されるのを防ぎます。

構文

sanitize_term_field( string $field, mixed $value, int $term_id, string $taxonomy, string $context );

引数の説明:

  • $field (string) — サニタイズするタームフィールドの名前(例: ‘name’, ‘description’など)。
  • $value (mixed) — サニタイズする値。
  • $term_id (int) — 関連するタームのID。
  • $taxonomy (string) — タームが属するタクソノミー(例: ‘category’, ‘post_tag’など)。
  • $context (string) — コンテキスト(例: ‘edit’, ‘display’, ‘db’など)。

使用例:

例 1. ターム名のサニタイズ

以下のコードは、指定されたターム名をサニタイズします。

<?php
$sanitized_name = sanitize_term_field( 'name', '不正な文字列<script>', get_term_by( 'slug', 'example', 'category' )->term_id, 'category', 'edit' );
?>

例 2. ターム説明のサニタイズ

ターム説明を安全に取得して保存します。

<?php
$term_id = get_term_by( 'slug', 'example', 'category' )->term_id;
$sanitized_description = sanitize_term_field( 'description', '<script>alert("XSS")</script>', $term_id, 'category', 'display' );
?>

例 3. タクソノミーのカスタムフィールドサニタイズ

カスタムフィールドの値をサニタイズします。

<?php
$custom_field = sanitize_term_field( 'custom_field', '不正なデータ<script>', get_term_by( 'slug', 'example', 'post_tag' )->term_id, 'post_tag', 'edit' );
?>

例 4. サニタイズ後にデータベースに保存

サニタイズされた値をデータベースに保存します。

<?php
$term_id = get_term_by( 'slug', 'example', 'category' )->term_id;
$sanitized_value = sanitize_term_field( 'name', '不正なデータ', $term_id, 'category', 'db' );
update_term_meta( $term_id, 'custom_meta_key', $sanitized_value );
?>

例 5. フロントエンド表示用の値サニタイズ

表示用にタームデータを安全に出力します。

<?php
$term_id = get_term_by( 'slug', 'example', 'category' )->term_id;
$display_name = sanitize_term_field( 'name', '不正なデータ', $term_id, 'category', 'display' );
echo esc_html( $display_name );
?>

注意点

  • 常に適切な$contextを指定してください。不適切なコンテキストは意図しないサニタイズ結果を引き起こす可能性があります。
  • 入力値が信頼できない場合は、この関数を使用してデータを検証してください。

関連機能: