ワードプレスのwp_headアクションの使用方法・解説

概要

wp_headアクションは、WordPressテーマのヘッダー部に追加の情報やスクリプト、スタイルを注入するために使用される非常に重要なアクションフックです。このアクションは、<head>タグの閉じタグ直前で呼び出されるため、WordPressを使ったサイトのメタデータやスタイルシート、JavaScriptファイルなどを簡単に追加することができます。

よく使われる機能

  • スタイルシートの追加
  • JavaScriptファイルの読み込み
  • メタタグの挿入
  • SEO関連のスクリプトの追加
  • テーマの設定情報の追加
  • 定義済みのフィルタフックの適用
  • カスタムスクリプトやスタイルの追加
  • Apple Touchアイコンやファビコンの指定

構文

do_action('wp_head');

パラメータ

wp_headアクションには、特定のパラメータは渡されません。

戻り値

このアクションは戻り値を持ちません。

関連する関数

wp_head

使用可能なバージョン

wp_headアクションは、WordPressのすべてのバージョンで使用可能です。

コアファイルのパス

wp-includes/general-template.php

この関数のアクションでの使用可能性

アクション名 使用可能性
mu_plugin_loaded
registered_post_type
plugins_loaded
wp_roles_init
setup_theme
after_setup_theme
set_current_user
init
register_sidebar
wp_loaded
send_headers
parse_query
pre_get_posts
wp
template_redirect
get_header
wp_head

サンプルコード

サンプルコード1: スタイルシートの追加

このサンプルコードでは、テーマのスタイルシートをwp_headアクションを使って追加します。

function my_custom_styles() {
    echo '<link rel="stylesheet" href="' . get_stylesheet_uri() . '" type="text/css" media="all" />';
}
add_action('wp_head', 'my_custom_styles');

引用元: https://developer.wordpress.org/reference/hooks/wp_head/

サンプルコード2: JavaScriptファイルの追加

このコードは、カスタムJavaScriptファイルをwp_headに追加します。

function my_custom_scripts() {
    echo '<script src="' . get_template_directory_uri() . '/js/custom-script.js"></script>';
}
add_action('wp_head', 'my_custom_scripts');

引用元: https://developer.wordpress.org/reference/hooks/wp_head/

サンプルコード3: メタタグの追加

このサンプルは、カスタムメタタグをヘッダーに追加します。

function my_custom_meta_tags() {
    echo '<meta name="description" content="My custom WordPress site" />';
}
add_action('wp_head', 'my_custom_meta_tags');

引用元: https://developer.wordpress.org/reference/hooks/wp_head/

サンプルコード4: カスタムフィードの追加

このサンプルは、テーマにカスタムRSSフィードを追加します。

function my_custom_feed() {
    echo '<link rel="alternate" type="application/rss+xml" title="My Feed" href="' . get_feed_link() . '" />';
}
add_action('wp_head', 'my_custom_feed');

引用元: https://developer.wordpress.org/reference/hooks/wp_head/

サンプルコード5: フォントの追加

このコードは、Google Fontsをwp_headに追加します。

function my_google_fonts() {
    echo '<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet" />';
}
add_action('wp_head', 'my_google_fonts');

引用元: https://developer.wordpress.org/reference/hooks/wp_head/

この関数について質問する


上の計算式の答えを入力してください