目次
Notice: Undefined variableエラーメッセージ全文
Notice: Undefined variable: add_class in ファイルパス/header.php on line 行数
Notice: Undefined variableエラー該当コード
header.php
<body <?php body_class($add_class); ?>>
Notice: Undefined variableエラーメッセージの意味
「Notice: Undefined variable」エラーは、PHPで未定義の変数を使用しようとした場合に表示される警告です。
Notice: Undefined variableエラーの原因
$add_classが未定義のためエラーが発生しています。
Notice: Undefined variableエラーを解決する方法
$add_classを定義すれば良い。
body_class($add_class)と引数を使用する理由
$add_class
と引数を使用することの一般的な用途は、特定のページや条件に基づいてカスタムの追加クラスをbody要素に追加することです。
例えば、固定ページのスラッグが「works」というページのbody要素のみに対して「abc」というクラス名をつけたい場合はbody_class($add_class)の前に下記を追加します。
<?php
if(is_page('works')) {
$add_class = 'abc';
} else {
$add_class = '';
}
?>
<body <?php body_class($add_class); ?>>
逆に特定のページにカスタムの追加クラスをbody要素に追加する必要がない場合はbody_class()に引数を使用する必要がありません。