PR
目次
Notice: Array to string conversion inエラー該当ソースコード
以下のソースコードはカスタム投稿タイプのカテゴリー一覧を表示するためのものです。
<?php
$post_type = get_post_type();
$taxonomy = get_object_taxonomies($post_type);
$args = array(
'taxonomy' => $taxonomy,
'hide_empty' => false,
'orderby' => 'description',
);
$case_terms = get_terms($args);
if($case_terms) :
usort($case_terms, function($a, $b) {
$descriptionA = intval($a->description);
$descriptionB = intval($b->description);
if ($descriptionA === $descriptionB) {
return 0;
}
return ($descriptionA < $descriptionB) ? -1 : 1;
});
foreach($case_terms as $case_term):
if($case_term->taxonomy === 'case_cat') {
$term_url = home_url('/' . $taxonomy . '/' . $case_term->slug);
echo '<a href="' . $term_url . '">' . $case_term->name . '</a>';
}
endforeach;
endif;
カスタム投稿タイプでカテゴリーの一覧を出力するソースコードは下記で紹介しています。
カテゴリー一覧表示部分で上記記事で紹介しているものとエラー該当ソースコードでは違う部分があるため今回のエラーが発生しています。
間違っているのはどの部分でしょうか?
また「’orderby’ => ‘description’」やusortの部分は上記記事にはありませんが、下記記事で紹介した、「カスタム投稿タイプのカテゴリーの並び順の変更」を実装している部分です。
Notice: Array to string conversion inエラーメッセージ全文
Notice: Array to string conversion in ファイルパス on line 行数
Notice: Array to string conversion inエラー該当箇所
$term_url = home_url('/' . $taxonomy . '/' . $case_term->slug);
上記でエラーが発生しているとわかるため、var_dumpしましょう。
Notice: Array to string conversion inエラー該当箇所をvar_dump
var_dump($term_url);
//出力結果
https://example.com/Array/スラッグ
エラー該当箇所でいう「$taxonomy」の部分が「Array」となっていることがわかります。
Notice: Array to string conversion inエラーメッセージの意味
このエラーメッセージは、PHPで配列を文字列として扱おうとしたときに発生します。
Notice: Array to string conversion inエラーメッセージを解決する方法
配列ではなく文字列として表示できれば良いです。
「$taxonomy」の部分もvar_dumpしてみましょう。
var_dump($term_url);
//出力結果
array(1) { [0]=> string(8) "case_cat" }
上記「$taxonomy」の部分が文字列の「case_cat」で表示されれば良さそうです。
なので「$taxonomy」を「$case_term->taxonomy」に変更します。
変更したところエラーが消えました。
修正後ソースコード
<?php
$post_type = get_post_type();
$taxonomy = get_object_taxonomies($post_type);
$args = array(
'taxonomy' => $taxonomy,
'hide_empty' => false,
'orderby' => 'description',
);
$case_terms = get_terms($args);
if($case_terms) :
usort($case_terms, function($a, $b) {
$descriptionA = intval($a->description);
$descriptionB = intval($b->description);
if ($descriptionA === $descriptionB) {
return 0;
}
return ($descriptionA < $descriptionB) ? -1 : 1;
});
foreach($case_terms as $case_term):
if($case_term->taxonomy === 'case_cat') {
$term_url = home_url('/' . $case_term->taxonomy . '/' . $case_term->slug);
echo '<a href="' . $term_url . '">' . $case_term->name . '</a>';
}
endforeach;
endif;