概要
set_theme_mod
関数は、現在のテーマ固有のプロパティ値を設定するために使用されます。これにより、テーマのカスタマイゼーションオプションを保存し、後で取得できるようになります。この関数は、テーマの設定やユーザーのカスタマイズを保存する際に役立ちます。具体的には、以下のような機能を実装する際によく使用されます。
- ヘッダー画像の設定
- カラースキームの選択
- ウィジェットエリアの設定
- フォントスタイルの管理
- ナビゲーションメニューの設定
- トップページの設定
- ソーシャルメディアリンクの保存
- カスタムロゴのアップロード設定
構文
set_theme_mod( $name, $value );
パラメータ
$name
(文字列): 設定するプロパティの名前を指定します。$value
(混合型): 設定する値を指定します。
戻り値
- この関数は、設定が正しく行われた場合には
true
を、失敗した場合にはfalse
を返します。
関連する関数
使用可能なバージョン
- WordPress 3.4.0 以降で利用可能です。
コアファイルのパス
wp-includes/theme.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 | 〇 |
サンプルコード
-
カスタムロゴを設定するサンプル
function mytheme_custom_logo() { $logo_url = 'http://example.com/wp-content/uploads/my-logo.png'; set_theme_mod('custom_logo', $logo_url); } add_action('after_setup_theme', 'mytheme_custom_logo');
このコードは、テーマがセットアップされる際にカスタムロゴのURLを設定します。
-
サイトのカラースキームを変更するサンプル
function mytheme_set_color_scheme() { $color_scheme = 'blue'; set_theme_mod('color_scheme', $color_scheme); } add_action('customize_register', 'mytheme_set_color_scheme');
チューニングレジスター時にブルーカラースキームを設定します。
-
デフォルトのヘッダー画像を設定するサンプル
function mytheme_default_header_image() { $header_image = 'http://example.com/wp-content/uploads/header-image.jpg'; set_theme_mod('header_image', $header_image); } add_action('after_setup_theme', 'mytheme_default_header_image');
ヘッダー画像をデフォルトで指定します。
-
初期ウィジェットエリアを設定するサンプル
function mytheme_register_sidebar() { register_sidebar(array( 'name' => 'Main Sidebar', 'id' => 'main-sidebar', 'before_widget' => '<div class="widget">', 'after_widget' => '</div>', 'before_title' => '<h2 class="widget-title">', 'after_title' => '</h2>', )); set_theme_mod('sidebar_position', 'right'); } add_action('widgets_init', 'mytheme_register_sidebar');
ウィジェットエリアを登録し、サイドバーの位置を設定します。
-
ソーシャルメディアリンクを保存するサンプル
function mytheme_set_social_links() { $social_links = array( 'facebook' => 'http://facebook.com/myprofile', 'twitter' => 'http://twitter.com/myprofile', ); set_theme_mod('social_links', $social_links); } add_action('after_setup_theme', 'mytheme_set_social_links');
ソーシャルメディアリンクをテーマのカスタマイズに追加します。