wp-config.php にデバッグログの出力設定を追加するだけのスクリプト


WordPress のデバッグ情報は基本的に表示されません。
しかし、構築中のときは何が起きているのかを知るのに役立ちます。
(特に真っ白な画面が出たとき)

エラーを画面上に表示すると、レイアウトが崩れてしまうのでデバッグログを出してます。
もちろん、本番稼働するときはコメントアウトして /wp-content/debug.log は消します。

define( 'WP_DEBUG', true );
define( 'WP_DEBUG_DISPLAY', false );
define( 'WP_DEBUG_LOG, true );

/* That's all, stop editing! Happy publishing. */

That's all 〜 のコメントの上に書くというルールがあるので
シェルスクリプトで末尾に追加できないという、少し面倒な仕様になってます。
それを何とかしただけのスクリプトがこちら。

スクリプト概要

  1. スクリプトを wp-config.php 付近に置きます。
  2. 実行するとバックアップ(wp-config.php.org1)を作成します。
  3. That's all 〜 のコメントの上にデバッグログの出力設定を追加します。
#!/bin/bash

# 対象ファイル名
target_file='./wp-config.php'

# 編集限界の位置を示す文字列
term_str="That's all, stop editing! Happy publishing."

# 文字列の検索
grep "$term_str" $target_file > /dev/null
if [ $? = 1 ]; then
  echo '[ERROR] 編集限界の位置を示す文字列が見つかりませんでした。'
  exit
fi

# 文字列の行数を取得
line=`grep -n "$term_str" $target_file | sed -e 's/:.*//g'`

# バックアップを取得
i=1
while [ -e ${target_file}.org${i} ]
do
  i=$(( i + 1 ))
done

cp $target_file ${target_file}.org${i}
if [ $? != 0 ]; then
  echo '[ERROR] 対象ファイルのバックアップでエラーが発生しました。'
  exit
fi

# 空行挿入フラグ
append=false

# WordPress デバッグ有効
grep "'WP_DEBUG'" $target_file > /dev/null

if [ $? = 1 ]; then
  sed -e $line'i\'$'\n'"define( 'WP_DEBUG', true );" -i $target_file
  line=$(( line + 1 ))
  append=true
fi

# WordPress デバッグ表示は無効
grep "'WP_DEBUG_DISPLAY'" $target_file > /dev/null

if [ $? = 1 ]; then
  sed -e $line'i\'$'\n'"define( 'WP_DEBUG_DISPLAY', false );" -i $target_file
  line=$(( line + 1 ))
  append=true
fi

# WordPress デバッグログは有効
grep "'WP_DEBUG_LOG'" $target_file > /dev/null

if [ $? = 1 ]; then
  sed -e $line'i\'$'\n'"define( 'WP_DEBUG_LOG', true );" -i $target_file
  line=$(( line + 1 ))
  append=true
fi

# 空行挿入して終了
if [ $append = true ]; then
  sed -e $line'i\'$'\n'$'\\\x0A' -i $target_file
fi

【補足】
Mac(BSD Linux 系)で動かすときは sed -i '' にする必要があるみたいです。

公開にした理由

多分、将来的に「あのスクリプトどこやったかな〜?」と探すことになると思ったので。