LoginSignup
19
12

More than 1 year has passed since last update.

WordPress6.1で追加された関数・クラス・アクション/フィルタ―フックまとめ

Last updated at Posted at 2022-09-24

はじめに

2022年11月1日に、WordPress 6.1がリリースされました。

この記事では、PHPコードに焦点を絞り、新たに追加された関数、アクションフック、フィルタ―フック・クラスをまとめたものです。

あわせて、WordPress6.1でアップデートまたは非推奨となったものも最後にまとめています。

条件として、WordPress本体のソース内で「PHPファイルの中で、コメントに @since 6.1.0 と記載があるもの」を手動で抽出してリストアップしました。

注意点

  • マイナーリリースにより、仕様が若干変わる可能性があります。最新の仕様は、WordPress の開発リポジトリまたは WordPress.org のリリースニュース (Make WordPress Core) などで確認してください。
  • 独断で「これは使えそう」「重要そう」と思った項目については、★マークを付けています。

関数

関数に関しては、以下のものを除外しています。

  • コメントのアクセス修飾子が private のもの(@access private
  • 関数名がアンダーバー始まり
  • おそらく内部的な利用にとどまるもの
  • 内部にフィルタ―フックが用意されており、直接呼ぶ事はおそらく想定されていないもの

did_filter

現在のリクエストの間にフィルターが適用された回数を取得します。

現在のリクエストの間にアクションが実行された回数を取得する did_action という関数がありますが、フィルターフックでも同様の事を行えるようになりました。引数には、フィルターフック名の文字列を渡します。

is_login

ログイン画面かどうかを判定します。

通常のログイン URL だけでなく、パスワード再発行画面や login_url フィルターフックで変更された URL にも対応してます。

is_term_publicly_viewable

タームが「閲覧可能」かどうかを取得します。

内部的に get_termis_taxonomy_viewable を持っているので、以下のようなコードをよりシンプルに書く事が出来ます。

before:

functions.php
$term = get_term( $term_id );
if ( ( $term instanceof WP_Term ) && is_taxonomy_viewable( $term->taxonomy ) ) {
	echo 'タームは閲覧可能です';
}

after:

functions.php
if ( is_term_publicly_viewable( $term_id ) ) {
	echo 'タームは閲覧可能です';
}

wp_get_latest_revision_id_and_total_count

投稿の最新のリビジョン ID とリビジョン数を取得します。

戻り値の配列には、latest_id (最新のリビジョン ID)、count (リビジョン数)が含まれます。リビジョン数の管理や削除を行うような機能を開発する時に役立つかもしれません。

フィルターフック

ajax_term_search_results

Ajax によるタームの検索結果をフィルタリングします。
Ajax でタームを検索する箇所というのは、具体的には以下です。

ajax_term_search_results_1.png

例えば以下のようなコードで、検索結果に常に独自のタグをサジェスト表示することが出来ます。

functions.php
<?php
function custom_ajax_term_search_results( $results, $taxonomy_object, $search ) {
	$add_tags = array( 'custom_tag_1', 'custom_tag_2', 'custom_tag_3' );
	return array_merge( $results, $add_tags );
}
add_filter( 'ajax_term_search_results', 'custom_ajax_term_search_results', 10, 3 );

ajax_term_search_results_2.png

第三引数でクエリも取得出来るので、独自の検索ロジックを組み込む事も出来るかもしれません。

block_core_navigation_render_inner_blocks

ナビゲーションブロックのインナーブロックをフィルタリングします。
メニュー項目をカスタマイズすることが出来るようです。

functions.php
<?php
function custom_block_core_navigation_render_inner_blocks( $inner_blocks ) {
	foreach ( $inner_blocks as $inner_block ) {
		if ( ! isset( $inner_block->parsed_block['attrs']['label'] ) ) {
			continue;
		}
		// 特定のメニューアイテムのラベル・URLを上書きする
		if ( 'Sample Page' === $inner_block->parsed_block['attrs']['label'] ) {
			$inner_block->parsed_block['attrs']['label'] = 'New Title';
			$inner_block->parsed_block['attrs']['url'] = 'https://example.com/new/';
		}
	}
	return $inner_blocks;
}
add_filter( 'block_core_navigation_render_inner_blocks', 'custom_block_core_navigation_render_inner_blocks' );

feed_links_extra_show_*_feed ★

これまでは、各フィードをオンオフするためのフィルターフックは、以下二つに限られていました。

上記二つのフックに加え、他のフィードについても出力の有無を制御出来るようになりました。

フィルターフック名 フィードのタイプ デフォルト値
feed_links_extra_show_author_feed 著者 true
feed_links_extra_show_category_feed カテゴリー true
feed_links_extra_show_search_feed 検索結果 true
feed_links_extra_show_post_comments_feed 投稿コメント feed_links_show_comments_feed フィルターフックの結果と同じ
feed_links_extra_show_post_type_archive_feed 投稿タイプアーカイブ true
feed_links_extra_show_tag_feed タグ true
feed_links_extra_show_tax_feed カスタムタクソノミー true

get_header_image

ヘッダー画像 URL をフィルタリングします。

ヘッダー画像とは、いわゆる「カスタムヘッダー画像」の事です。

functions.php
// カスタムヘッダー機能の有効化
add_theme_support('custom-header');

function custom_get_header_image( $url ) {
	// ヘッダー画像URLを書き換える
	return 'https://example.com/new_image.jpg';
}
add_filter( 'get_header_image', 'custom_get_header_image' );

lost_password_html_link

パスワードリセットページへのリンクHTMLをフィルタリングします。

lost_password_html_link_1.png

functions.php
function custom_lost_password_html_link( $html_link ) {
	$html_link = sprintf(
		'<a href="%s">%s</a>',
		esc_url( wp_lostpassword_url() ),
		'パスワードを忘れたときはここをクリック!'
	);
	return $html_link;
}
add_filter( 'lost_password_html_link', 'custom_lost_password_html_link' );

lost_password_html_link_2.png

post_class_taxonomies ★

投稿記事用に生成する CSS クラスのうち、タクソノミーに関する CSS クラスをフィルタリングします。

投稿記事をステータスに応じて CSS でコントロールしたい時、以下のように post_class (または get_post_class)をコンテナ要素に使用する場合があると思います。

functions.php
<div <?php post_class(); ?>>
	<?php the_content(); ?>
</div>

この時、多数のターム (カテゴリー、タグなど) が投稿に紐づけられている場合、以下のように出力されるクラス名も非常に長くなります。

<div class="post-xxx post type-post status-publish format-standard hentry category-cat_a category-cat_b category-cat_c tag-tag_a tag-tag_b tag-tag_c entry">
	コンテンツが入ります。
</div>

このフックを使うと、多数のクラスが生成される事を防いだり、また多数のタームを持つサイトのパフォーマンスを向上させる事が出来ます。タクソノミーに関する CSS クラスを全て表示させたくないのであれば、以下のようなコードとなります。

functions.php
function custom_post_class_taxonomies( $taxonomies, $post_id, $classes, $class ) {
	return array();
}
add_filter( 'post_class_taxonomies', 'custom_post_class_taxonomies', 10, 4  );

上記フィルターフックを適用すると、出力例は以下のようになります。

<div class="post-xxx post type-post status-publish format-standard hentry entry">
	コンテンツが入ります。
</div>

pre_option

取得するオプションの値を取得する前にフィルタリングします。

このフィルターフックで false 以外を返すと、データベースからオプション値などを取得する処理がバイパスされ、このフックの戻り値が値となります。

不用意に書き換えると不具合の原因になるかもしれませんので、使用する際は注意して下さい。

functions.php
function custom_pre_option( $pre_option, $option, $default ) {
	// 特定のオプション名の時に特定の値を返す
	if ( 'xxx' === $option ) {
		return 'new_option_value';
	}
	return $pre_option;
}
add_filter( 'pre_option', 'custom_pre_option', 10, 3 );

またこのフィルターフックの前段に、特定のオプション名の時だけフィルタリングする pre_option_{$option} があります。

pre_wp_list_authors_post_counts_query

投稿者の一覧を表示する wp_list_authors で、パラメータの optionscounttrue にした時に、出力されるユーザー名に投稿数が表示されます。 この投稿数のクエリをバイパスし、事前に指定出来るフックです。

キーに投稿者 ID、値に投稿数を含めた配列を返却する必要があり、以下コード例では全ユーザの投稿数を固定値にしていますが、実際はカスタム投稿数や投稿ステータスを考慮した動的な値をユーザー別に指定する事になると思います。

functions.php
function custom_pre_wp_list_authors_post_counts_query( $post_counts, $parsed_args ) {
	$authors         = get_users( $parsed_args );
	$new_post_counts = array();

	foreach ( $authors as $author ) {
		// 各投稿者の投稿数を変更する
		// 実際は、ここで投稿数にカスタム投稿の数などを加算する
		$new_post_counts[ $author->ID ] = 10;
	}
	return $new_post_counts;
}
add_filter( 'pre_wp_list_authors_post_counts_query', 'custom_pre_wp_list_authors_post_counts_query', 10, 2 );

query_loop_block_query_vars

クエリループブロックの WP_Query に渡される引数をフィルタリングします。

注意点としては、フィルタが反映されるのはフロントエンドのみという事、ブロックの設定で「テンプレートからクエリーを継承」がオンになっているとフィルタを通過しないという点です。

functions.php
function custom_query_loop_block_query_vars( $query, $block, $page ) {
	// クエリーループブロックで表示する投稿件数を変更する
	$query[ 'posts_per_page' ] = 5;
	return $query;
}
add_filter( 'query_loop_block_query_vars', 'custom_query_loop_block_query_vars', 10, 3 );

rest_json_encode_options ★

REST API のレスポンス送信に使用する JSON エンコーディングのオプションをフィルタリングします。

第一引数の $optionsjson_encode() の第二引数 ($flags) なので、ビットマスクです。そのため、フラグを立てる時はビット代入演算子を使うと分かりやすいと思います。

開発中、REST API のレスポンスを見やすくしたい時に便利だと思います。

functions.php
function custom_rest_json_encode_options( $options, $request ) {
	// 「/」をエスケープしない
	$options |= JSON_PRETTY_PRINT;
	// 返される結果の書式をスペースを使って整える
	$options |= JSON_UNESCAPED_SLASHES;
	return $options;
}
add_filter( 'rest_json_encode_options', 'custom_rest_json_encode_options', 10, 2 );

ブラウザで直接エンドポイントを叩いた時、フィルター適用前後の表示は以下のようになります。

before:

rest_json_encode_options_1.png

after:

rest_json_encode_options_2.png

site_status_good_response_time_threshold

ページキャッシュが有効である時に、サーバーの応答時間が良好であるとみなす閾値 (ミリ秒) をフィルタリングします。

functions.php
function custom_site_status_good_response_time_threshold( $threshold ) {
	// デフォルトは600ミリ秒
	return 600;
}
add_filter( 'site_status_good_response_time_threshold', 'custom_site_status_good_response_time_threshold' );

site_status_page_cache_supported_cache_headers

コアがサポートするキャッシュヘッダのリストをフィルタリングします。

このリストは、サイトヘルスページでページキャッシュが有効化どうかを判定する基準として、また無効である場合の説明文に表示するテキストとして使用されます。キャッシュヘッダについてはあまり詳しくありませんが、特定のベンダーが使用するキャッシュヘッダーを追加したりするようです。

site_status_page_cache_supported_cache_headers.png

functions.php
function custom_site_status_page_cache_supported_cache_headers( $cache_headers ) {
	// コアがサポートするキャッシュヘッダのリストを変更する
	// 以下はデフォルト値
	return array(
		'cache-control'          => static function ( $header_value ) {
			return (bool) preg_match( '/max-age=[1-9]/', $header_value );
		},
		'expires'                => static function ( $header_value ) {
			return strtotime( $header_value ) > time();
		},
		'age'                    => static function ( $header_value ) {
			return is_numeric( $header_value ) && $header_value > 0;
		},
		'last-modified'          => '',
		'etag'                   => '',
		'x-cache-enabled'        => static function ( $header_value ) {
			return 'true' === strtolower( $header_value );
		},
		'x-cache-disabled'       => static function ( $header_value ) {
			return ( 'on' !== strtolower( $header_value ) );
		},
		'x-srcache-store-status' => static function ( $header_value ) {
			return false !== strpos( strtolower( $header_value ), 'hit' );
		},
		'x-srcache-fetch-status' => static function ( $header_value ) {
			return false !== strpos( strtolower( $header_value ), 'hit' );
		},
	);
}
add_filter( 'site_status_page_cache_supported_cache_headers', 'custom_site_status_page_cache_supported_cache_headers' );

site_status_available_object_cache_services / site_status_page_cache_supported_cache_headers / site_status_persistent_object_cache_notes / site_status_persistent_object_cache_url / site_status_should_suggest_persistent_object_cache / site_status_persistent_object_cache_thresholds

6.1 では、サイトヘルスページにオブジェクトキャッシュに関するテスト項目が追加されます。これらのフィルターフックは、そのオブジェクトキャッシュに関する設定や情報をフィルタリングします。

これらのフィルタは、ホスティングプロバイダの環境に応じて、より具体的な情報をユーザーに伝えるために追加されたようです。

事前の確認点として、このフィルターフックをテストする場合は、WordPressが「production 環境」であることが必要です。つまり、wp_get_environment_type の戻り値が production であるという事です。production 以外 (local, development, staging ) の場合は、サイトヘルスにはオブジェクトキャッシュに関する情報が表示されません。

デフォルト値は production のはずですが、自分のローカル環境 (旧 Local By Flywheel) ではこの値が local となり、wp-config.php で以下定数を定義しても変わりませんでした。

wp-config.php
define( 'WP_ENVIRONMENT_TYPE', 'production' );

この記事によると、Local は bootstrap ファイルで WP_ENVIRONMENT_TYPElocal に設定されており、 wp-config.php ファイルでは上書き出来ないようです。

Local version 6.4.3 では、Windows の場合は以下ファイルで定数が定義されていたため、ここを書き換える事で対応しました。

C:\Program Files (x86)\Local\resources\extraResources

また、 この定数をもとに本番環境用の処理を行っている場合などは、定数を production に変更する事で意図しない処理・不具合が発生する場合があります。十分注意した上で、自己責任で設定して下さい。

フィルターフック名 フィルタリングする情報・設定
site_status_available_object_cache_services オブジェクトキャッシュサービスのリスト。オブジェクトキャッシュの利用を推奨する時に表示される。
site_status_persistent_object_cache_notes オブジェクトキャッシュが有効ではない時に、有効にする事を推奨する説明文の二つ目の段落テキスト。
site_status_persistent_object_cache_url Learn more about persistent object caching. リンクの URL。
site_status_should_suggest_persistent_object_cache オブジェクトキャッシュを推奨するかどうか
site_status_persistent_object_cache_thresholds オブジェクトキャッシュの使用を推奨するかどうかを決定するために使用する閾値

上記フックを使ったコード例はこのようになります。

functions.php
function custom_site_status_persistent_object_cache_url( $action_url ) {
	// Learn more... リンクの URLを変更する
	return 'https://example.com';
}
add_filter( 'site_status_persistent_object_cache_url', 'custom_site_status_persistent_object_cache_url' );
functions.php
function custom_site_status_available_object_cache_services( $action_url ) {
	// 提案するオブジェクトキャッシュサービスのリストを変更する
	return 	array(
		'custom_service_1',
		'custom_service_2',
		'custom_service_3',
	);
}
add_filter( 'site_status_available_object_cache_services', 'custom_site_status_available_object_cache_services' );

function custom_site_status_persistent_object_cache_notes( $notes, $available_services ) {
	// オブジェクトキャッシュを推奨する時の二つ目の説明文を変更する
	return sprintf(
		'次のサービスをおすすめします。%s',
		implode( '、', $available_services )
	);
}
add_filter( 'site_status_persistent_object_cache_notes', 'custom_site_status_persistent_object_cache_notes', 10, 2 );

object_cache_1.png

functions.php
// オブジェクトキャッシュが有効になっていない時に、利用を推奨しない
add_filter( 'site_status_should_suggest_persistent_object_cache', '__return_false' );

object_cache_2.png

functions.php
function custom_site_status_persistent_object_cache_thresholds( $thresholds ) {
	// オブジェクトキャッシュの使用を推奨するかどうかを決定するために使用する閾値を変更する
	// 以下はデフォルト値であり、環境に応じて適宜上書きする
	return array(
		'alloptions_count' => 500,    // 全てのオプション (wp_load_alloptions) の数
		'alloptions_bytes' => 100000, // 全てのオプション (wp_load_alloptions) のバイト数
		'comments_count'   => 1000,   // 全てのコメント件数
		'options_count'    => 1000,   // 全てのオプション数
		'posts_count'      => 1000,   // 全ての投稿件数
		'terms_count'      => 1000,   // 全てのターム数
		'users_count'      => 1000,   // 全てのユーザー数
	);
}
add_filter( 'site_status_persistent_object_cache_thresholds', 'custom_site_status_persistent_object_cache_thresholds' );

the_posts_pagination_args

the_posts_pagination (get_the_posts_pagination) のパラメータをフィルタリングします。

このフックが追加された理由のユースケースの一つとして、子テーマでページネーションを書き換える例が挙げられていました。例えば、子テーマ側でページネーションの出力を上書きしたい場合、その関数が含まれているファイルをコピーしてパラメータを書き換えるか、paginate_links_output などのフックで出力される HTML を書き換えるしか方法がありませんでした。前者であれば、親テーマのテンプレート構造の更新に追従する必要があり、後者は出力される HTML によっては正しく置換出来ないかもしれません。

このフックを使えば、子テーマにテンプレートを追加する必要がなくなり、親テーマの更新に柔軟に追従する事が出来ます。

functions.php
function custom_posts_pagination_args( $args ) {
	// 前のページ・次のページへのリンクテキストを上書きする
	$args['prev_text'] = '前のページに移動します';
	$args['next_text'] = '次のページに移動します';
	return $args;
}
add_filter( 'the_posts_pagination_args', 'custom_posts_pagination_args' );

wp_list_table_class_name

インスタンス化するリストテーブルクラスをフィルタリングします。

管理画面では、投稿・コメント・ユーザーなど様々な場所で表 (リスト) が使用されていますが、それらのリストを生成している元となるものが WP_List_Table クラスで、ページに応じた継承クラス (WP_Posts_List_TableWP_Media_List_Table ) が使用されています。

WP_List_Table についてはあまり詳しくありませんが、おそらくこれまで通り WP_List_Table クラスを継承した独自クラスを定義した上で、このフック内でそのクラス名を指定すれば、自動的にインスタンス化してくれるのではないかと思います。

functions.php
function custom_wp_list_table_class_name( $class_name, $args ) {
	if ( 'book' === $args['screen']->post_type ) {
		return 'WP_My_Custom_List_Table';
	}
	return $class_name;
}
add_filter( 'wp_list_table_class_name', 'custom_wp_list_table_class_name', 10, 2 );

wp_theme_json_data_default / wp_theme_json_data_blocks / wp_theme_json_data_theme / wp_theme_json_data_user

theme_json の各種設定をフィルタリングします。

Gutenberg からコアにバックポートされたもので、それぞれ以下のデータをフィルタリングします。

フィルターフック名 フィルタリングする対象
wp_theme_json_data_default コアから提供されるデータ
wp_theme_json_data_blocks ブロックから提供されるデータ
wp_theme_json_data_theme テーマから提供されるデータ
wp_theme_json_data_user ユーザーから提供されるデータ

いずれも、コールバック関数の引数には WP_Theme_JSON_Data クラスのインスタンスが渡ってきます。これらのフィルターフックは強力で、 theme.json の仕組みを理解している必要がありますが、コードの一例を記載します。

functions.php
function custom_wp_theme_json_theme( $theme_json ) {
	$new_data = array(
		'version'  => 2,
		'settings' => array(
			'color'  => array(
				// テキストカラーのUIを無効にする
				'text'  => false,
			),
			// CSS変数を追加する (--wp-custom--my-plugin--sm: 1em)
			'custom' => array(
				'my-plugin' => array(
					'sm' => '1em',
				)
			),
		),
		'styles'   => array(
			'elements' => array(
				'h2' => array(
					'typography' => array(
						// h2要素のフォントサイズを変更する
						'fontSize' => '2rem',
					),
				),
			),
		),
	);
	return $theme_json->update_with( $new_data );
}
add_filter( 'wp_theme_json_data_theme', 'custom_wp_theme_json_theme' );

wp_theme_json_get_style_nodes

Gutenberg からコアにバックポートされたもので、「インライン CSS 出力のベースとなるスタイルノード」をフィルタリングします。

ここでいうインライン CSS というのは、「グローバルスタイルによって出力される CSS」の事であり、コールバック関数の引数には例えば以下のようなデータが渡ってきます。

array(
	array(
		'path' => array(
			'styles',
			'elements',
			'h1',
		),
		'selector' => 'h1',
	),
	array(
		'path' => array(
			'styles',
			'elements',
			'button',
		),
		'selector' => '.wp-element-button, .wp-block-button__link',
	),
	array(
		'name' => 'core/post-title',
		'path' => array(
			'styles',
			'blocks',
			'core/post-title',
		),
		'selector' => '.wp-block-post-title',
		'duotone' => null,
		'features' => null,
	),
	// ...
)

これらのスタイルノードをもとにして CSS が出力されるようで、完全には理解していないためコード例は示せないのですが、ブロックの CSS を独立して読み込む時などに使用されるフックのようです。

update_themes_{$hostname} ★

6.1で、テーマが Update URI ヘッダをサポートしました。

このヘッダが導入された理由として、独自に配布しているサードパーティ製のテーマの場合、更新に関しての以下二つの問題点がある事がもとになっていると思います。

  • 同名のテーマと衝突する可能性がある (テーマディレクトリに登録されているテーマスラッグと同じ場合、後者のアップデートにより自作テーマが上書きされてしまう)
  • 更新チェック機能を実装する必要がある

上記一点目の問題は、Update URI ヘッダをサポートした事で、同名テーマとの衝突を避ける事が出来るようになりました。二点目の問題については、update_themes_{$hostname} フィルターフックを使用する事で、より手軽に更新機能を実装出来るようになりました。

なおプラグインに関しては、5.8.0で Update URI フィールドをサポートしており、update_plugins_{$hostname} という同様のフィルターフックが存在します。手前味噌ですが、【WordPress5.8】新しいフック+GitHub APIで自作プラグインに更新通知を追加する という記事で、update_themes_{$hostname} フィルターフックを使用した更新機能の実装方法を解説しています。テーマにおいても、ほぼ同じ考え方・実装方針が使えると思います。

wp_img_tag_add_decoding_attr ★

フロントエンド側で、画像に decoding="async"属性が付与されるようになりますが、この属性の有無や値をフィルタリングします。

functions.php
// decoding 属性を sync に変更する
function custom_img_tag_add_decoding_attr( $value, $image, $context ) {
	return 'sync';
}
add_filter( 'wp_img_tag_add_decoding_attr', 'custom_img_tag_add_decoding_attr', 10, 3 );

// decoding 属性を付与しない
add_filter( 'wp_img_tag_add_decoding_attr', '__return_false' );

なお、このフィルタを通過するのはコンテンツとして出力される画像のみです。 wp_get_attachment_image などの関数で出力する画像にも decoding="async" 属性がデフォルトで付与されるようになりますが、これを変更するには、 wp_get_attachment_image_attributes フィルターフックを使用します。

functions.php
// decoding 属性を sync に変更する
function custom_get_attachment_image_attributes( $attr, $attachment, $size ) {
	$attr['decoding'] = 'sync';
	return $attr;
}
add_filter( 'wp_get_attachment_image_attributes', 'custom_get_attachment_image_attributes', 10, 3 );

wp_list_authors_args

投稿者の一覧を表示する wp_list_authors のパラメータをフィルタリングします。

functions.php
function custom_list_authors_args( $query_args, $parsed_args ) {
	// 並び順をデフォルトの昇順から降順に変更する
	$query_args['order'] = 'DESC';
	// 除外するユーザーIDを追加する
	if ( '' !== $query_args['exclude'] && ! is_array( $query_args['exclude'] ) ) {
		$query_args['exclude'] = explode( ',', $query_args['exclude'] );
		$query_args['exclude'] = array_map( 'intval', $query_args['exclude']  );
	}
	$query_args['exclude'] = array_merge( $query_args['exclude'], array( 11 ) );
	return $query_args;
}
add_filter( 'wp_list_authors_args', 'custom_list_authors_args', 10, 2 );

wp_list_users_args

ユーザーの一覧を表示する wp_list_users のパラメータをフィルタリングします。

パラメータの種類やデフォルト値は wp_list_authors_args と似ているので、wp_list_authors_args のコード例を参照して下さい。

wp_preload_resources ★

読み込むリソースに preload 属性を付与するためにフィルターフックです。

どのリソースをプリロードするか、またどのような属性を指定するかはサイトによって大きく変わってくると思いますが、以下の例のように配列で指定します。

functions.php
function custom_preload_resources() {
	return array(
		// CSS
		array(
			'href' => get_template_directory_uri() . '/style.css',
			'as'   => 'style',
			'type' => 'text/css',
		),
		// JavaScript
		array(
			'href' => get_template_directory_uri() . '/script.js',
			'as'   => 'script',
		),
		// Web フォント
		array(
			'href' => get_template_directory_uri() . '/font.woff2',
			'as'   => 'font',
			'type' => 'font/woff2',
			'crossorigin',
		),
		// 動画
		array(
			'href' => get_template_directory_uri() . '/video.mp4',
			'as'   => 'video',
			'type' => 'video/mp4',
		),
		// 画像 (レスポンシブ)
		array(
			'href' => get_template_directory_uri() . '/image.jpg',
			'as'   => 'image',
			'media' => '(min-width: 601px)',
		)
	);
}
add_filter( 'wp_preload_resources', 'custom_preload_resources' );

wp_read_audio_metadata

音声ファイルのメタデータをフィルタリングします。

どのようなケースで使用するのか思いつきませんが、以下のようなコードでフィルタリングする事が出来ます。

functions.php
function custom_read_audio_metadata( $metadata, $file, $file_format, $data ) {
	// ここで何かメタ情報を追加する
	return $metadata;
}
add_filter( 'wp_read_audio_metadata', 'custom_read_audio_metadata', 10, 4 );

$metadata には、例えば以下のようなデータが渡ってきます。

Array(
    [dataformat] => mp3
    [channels] => 2
    [sample_rate] => 44100
    [bitrate] => 128000
    [channelmode] => joint stereo
    [bitrate_mode] => cbr
    [lossless] => 
    [encoder_options] => CBR128
    [compression_ratio] => 0.090702947845805
    [fileformat] => mp3
    [filesize] => 2204679
    [mime_type] => audio/mpeg
    [length] => 138
    [length_formatted] => 2:18
)

ちなみに、画像ファイルと動画ファイルにも、同様のフィルターフックが用意されています。

  1. 画像: wp_read_image_metadata
  2. 動画: wp_read_video_metadata

wp_required_field_indicator / wp_required_field_message

フォームの必須項目について、wp_required_field_indicator は視覚的なマークアップを、wp_required_field_message は説明文のマークアップをフィルタリングします。

「フォームの必須項目」とは、具体的には以下のような箇所です。

  • コメントフォームのコメント入力欄のタイトル
  • マルチサイトで新しいサイトを追加する時の「サイトアドレス」「サイトタイトル」「管理者メールアドレス」
functions.php
<?php
function custom_required_field_indicator( $indicator ) {
	// フォームの必須項目について、視覚的なマークアップを変更する
	// *デフォルトのマークアップ
	// <span class="required">*</span>
	return '<span class="custom-required">★</span>';
}
add_filter( 'wp_required_field_indicator', 'custom_required_field_indicator' );

function custom_required_field_message( $message ) {
	// フォームの必須項目について、説明文のマークアップを変更する
	// *デフォルトのマークアップ
	// <span class="required-field-message"><span class="required">*</span> が付いている欄は必須項目です</span>
	// 「*」には、wp_required_field_indicator フィルターも反映される
	return '<span class="custom-required-field-message">★が付いている欄を入力してください</span>';
}
add_filter( 'wp_required_field_message', 'custom_required_field_message' );

before:

wp_required_field_indicator_1.png

after:

wp_required_field_indicator_2.png

wp_send_new_user_notification_to_admin / wp_send_new_user_notification_to_user

新しいユーザーの登録を通知する wp_new_user_notification 関数に追加された二つのフィルターフックです。

目的に応じて、メールを送信するかどうかをフィルタリングします。

  • wp_send_new_user_notification_to_admin: 管理者にユーザー登録を通知するかどうか
  • wp_send_new_user_notification_to_user: 新しいユーザーにログインユーザー名とパスワード設定用リンク URL を通知するかどうか

wp_new_user_notification はプラガブル関数であるため、テーマやプラグインで上書きする事が出来ます。これまでは、メールを通知するかどうかを決定するフックがコア関数に存在しなかったため、その機能を実装するためにはコア関数をコピーした上でカスタマイズする必要がありました。

このフックを利用すれば、関数を上書きしなくても済むケースもあると思います。

functions.php
function custom_send_new_user_notification_to_admin( $send, $user ) {
	// 「購読者」権限のユーザーが追加された場合は、管理者にメールを送信しない
	if ( in_array( 'subscriber', $user->roles, true ) ) {
		return false;
	}
	return $send;
}
add_filter( 'wp_send_new_user_notification_to_admin', 'custom_send_new_user_notification_to_admin', 10, 2 );

function custom_send_new_user_notification_to_user( $send, $user ) {
	// ユーザー名に「test」が含まれている場合は、ユーザーにメールを送信しない
	if ( strpos( $user->data->user_login, 'test' ) !== false ) {
		return false;
	}
	return $send;
}
add_filter( 'wp_send_new_user_notification_to_user', 'custom_send_new_user_notification_to_user', 10, 2 );

アクションフック

cron_reschedule_event_error / cron_unschedule_event_error

cron イベントの再スケジューリングを行う wp_reschedule_event 関数、 スケジュールの解除を行う wp_unschedule_event で、エラーログが出力されるようになりました。

同時に、エラー発生時に追加の動作を行う事が出来るように、二つのフックが追加されました。

  1. cron_reschedule_event_error: cron イベントの再スケジューリングでエラーが発生した場合
  2. cron_unschedule_event_error: cron イベントのスケジュール解除でエラーが発生した場合

wp_before_load_template / wp_after_load_template

テンプレートファイルが読み込まれる前・読み込まれた後に発火します。

ここで言うテンプレートファイルとは、フルサイト編集のテンプレートのことではなく、 get_header()get_template_part で読み込まれるファイルの事です。そのため、おそらくブロックテーマでは発火せず、クラシックテーマ向けに追加されたフックではないかと思います。

これは、テンプレート読み込みのタイミングデータなどのデバッグ情報の収集に役立てる事が目的のようです。

functions.php
function custom_after_load_template( $_template_file, $require_once, $args ) {
	//  Unix タイムスタンプ (マイクロ秒まで) とファイルパスをログに記録する
	error_log( microtime( true ) . ' - ' . $_template_file );
}
add_action( 'wp_before_load_template', 'custom_after_load_template', 10, 3 );

クラス

クラスに関しては、一般的な開発ではほぼ使わないであろう事、また自分が詳しく解説出来る自信がありませんので、各クラスの冒頭のコメント欄を翻訳した文章のみ記載しておきます。

WP_Style_Engine

他の全ての WP_Style_Engine_* クラスを統合するメインクラス

WP_Style_Engine_Processor

ストアやCSSルールのコレクションからスタイルをコンパイルする

WP_Style_Engine_CSS_Declarations

CSS ルール宣言を保持、サニタイズ、表示する

WP_Style_Engine_CSS_Rule

CSS ルールのオブジェクト

WP_Style_Engine_CSS_Rules_Store

WP_Style_Engine_CSS_Rule オブジェクトのストア

WP_Textdomain_Registry

ロケールAPI

WP_Theme_JSON_Data

(コメント無し)

アップデートされた関数

影響が大きそうな関数のみをピックアップしています。

add_settings_section

第五引数で、追加されるHTMLのラッパーやクラス名を追加出来るようになりました。

functions.php
function add_general_custom_sections() {
	add_settings_section(
		'my-custom',
		'カスタムセクション',
		function() {
			echo 'カスタムセクションの説明';
		},
		'general',
		array(
			// 特定のクラス名でセクションをラップする
			'before_section' => '<div class="%s">',
			'after_section' => '</div>',
			'section_class' => 'my-custom-class',
		)
	);
}
add_action( 'admin_init', 'add_general_custom_sections' );

add_settings_section.png

esc_url_raw ★

同様の関数として sanitize_url があり、これまで sanitize_urlesc_url_raw のエイリアスでした。

6.1ではこれが逆になり、esc_url_rawsanitize_url のエイリアスとなります。

これにより、WordPress コアの esc_url_raw が全て sanitize_url に置換され、データベースやリダイレクト用の URL をサニタイズするための関数として、sanitize_url が推奨されるようになりました。

register_block_type (register_block_type_from_metadata) ★

render フィールドのサポートが追加されました。

これはダイナミックブロックに関連しますが、レンダリングにPHPファイルを指定する場合、例えば以下のような書き方をしていたと思います。

functions.php
function my_block_dynamic_block_init() {
	// ダイナミックブロックを登録
	register_block_type(
		__DIR__ . '/build/',
		array(
			// コールバック関数を指定
			'render_callback' => 'my_block_render_callback',
		)
	);
}
add_action( 'init', 'my_block_dynamic_block_init' );

function my_block_render_callback( $attributes, $content ) {
	// ダイナミックブロック用のPHPファイルを読み込み
	ob_start();
	require plugin_dir_path( __FILE__ ) . 'build/template.php';
	return ob_get_clean();
}

block.jsonrender フィールドを使えるようになった事で、直接テンプレートファイルを指定出来るので、PHP 側をよりシンプルに記述出来るようになります。

functions.php
function my_block_dynamic_block_init() {
	register_block_type( __DIR__ . '/build/' );
}
add_action( 'init', 'my_block_dynamic_block_init' );
block.json
{
  "$schema": "https://schemas.wp.org/trunk/block.json",
  "apiVersion": 2,
  "name": "gutenberg-example/my-block",
  "title": "My Block",
  "category": "text",
  "icon": "smiley",
  "textdomain": "gutenberg-example",
  "editorScript": "file:./index.js",
  "render": "file:./template.php"
}

safecss_filter_attr

インラインスタイル属性をフィルタリングする関数ですが、--color: #F00 のようなCSS変数への値の代入、min()max()clamp() などをサポートしました。

wp_get_attachment_image

画像に decoding="async" 属性がデフォルトで付与されるようになりました。この属性を変更するには、wp_get_attachment_image_attributes フィルターフックを使用します (6.1では、第一引数の $attrdecoding 属性が含まれるようになっています )。

アップデートされたフィルタ―フック

影響が大きそうなものは特に無し

アップデートされたアクションフック

影響が大きそうなものは特に無し

非推奨となった関数

global_terms / global_terms_enabled / install_global_terms / sync_category_tag_slugs

「WordPress MU」は、WordPress にマルチサイト機能が無かった頃のプロジェクトで、WordPress3.0.0でコアに取り込まれ、開発終了となったようです。

この4つの関数はその WordPress MU 向けの関数のようですが、6.1で非推奨となりました。

おそらく、これらの関数を今使っているテーマ・プラグインは無いでしょうから、気にする必要はないと思います。

19
12
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
12