【SWELL】Warning:Undefined array key 0 in /wp-content/themes/swell/classes/Utility/Get.php on line 805 エラーの対処法

当ページのリンクには広告が含まれています。

WordPressの有料テーマ「SWELL」を使用している際、記事のカテゴリー名表示箇所に以下のエラーが表示される場合があります。

Warning:Undefined array key 0 in /wp-content/themes/swell/classes/Utility/Get.php on line 805

とか

Warning:Undefined array key 0 in /wp-content/themes/swell/classes/Utility/Get.php on line 804

とか。

目次

エラーの原因

このエラーが出る原因は以下の場合です。

  • カスタムタクソノミーを設定している
  • カスタムタクソノミーに階層を持たせている

エラーが出ているファイルは、SWELLの親テーマの中swell/classes/Utility/Get.php

805行目を見てみると・・・

// 階層を保つ場合は親から順に並べる
if ( is_taxonomy_hierarchical( $tax ) ) {
  $term_tree = [];
  foreach ( $terms as $term ) {
  $self_id = $term->term_id;
  $parent_id = $term->parent; $term_data = [
                'id'   => $term->term_id,
                'slug' => $term->slug,
                'name' => $term->name,
                'url'  => get_term_link( $term ),
            ];

            $acts_ct    = 0;
            $top_act_id = $self_id;
            if ( $parent_id ) {
                // 先祖リストを取得
                $ancestors  = array_reverse( get_ancestors( $term->term_id, 'category' ) );
                $acts_ct    = count( $ancestors );
                $top_act_id = $ancestors[0];
            }

$top_act_id = $ancestors[0];が取得できない状態です。

$ancestors は array_reverse( get_ancestors( $term->term_id, 'category' ) ); と指定されていますが、ここでcategoryのみが指定されているため、カスタムタクソノミーを設定している記事でエラーにるというわけです。

対処法

変更する前に必ずバックアップを取りましょう

swell/classes/Utility/Get.phpのコードを修正する

805行目を書き換える対処法です。アップデートがあるたびにエラーは戻るので、あまりお勧めできません。

SWELLの親テーマを変更することになるため、バージョンアップ時は上書きされて元に戻ることがある為、都度の書き換えが必要になります。

$ancestors = array_reverse( get_ancestors( $term->term_id, $term->taxonomy ) );

Warning表示をさせないようにする

エラー表示(Warning:)を出力させないようにする設定があります。

エラーの根本的な解決ではありません。

その設定をすることにより、Warningの表示は消えますが、その他にエラーがある場合でも表示されなくなってしまいます。

★オススメ:子テーマのfunctionに対処コードを追加する

通常のカテゴリーじゃないくタクソノミーである場合の処理を追加します。

下記コード13行目から始まる$custom_taxonomiesに、register_taxonomyで追加したタクソノミー定義します。

子テーマのregister_taxonomyコードの下(function.php等)に、下記コードのtaxonomy_a, taxonomy_b を自身のタクソノミーに置き換えて記述します。

/**
 * SWELLの get_the_terms_data() 内で
 * カスタムタクソノミーの親ターム取得時に
 * 'category' が固定されている問題を補正
 */
add_filter( 'get_ancestors', function( $ancestors, $object_id, $object_type, $resource_type ) {

	// SWELLが category として取得しようとしている場合だけ
	if ( 'category' !== $object_type ) {
		return $ancestors;
	}

	// カスタムタクソノミーを確認
	$custom_taxonomies = [
		'taxonomy_a',
		'taxonomy_b',
	];

	foreach ( $custom_taxonomies as $taxonomy ) {

		$term = get_term( $object_id, $taxonomy );

		if ( $term && ! is_wp_error( $term ) ) {

			// 親を持つカスタムタクソノミーだった場合
			if ( ! empty( $term->parent ) ) {
				return get_ancestors(
					$object_id,
					$taxonomy,
					'taxonomy'
				);
			}

			// 親がない場合は空配列
			return [];
		}
	}

	return $ancestors;

}, 10, 4 );

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!
目次