?
実現したいこと
カテゴリーがない個別投稿ページでもエラーなく
表示したい
前提
sidebar.phpで
表示している投稿ページと同じカテゴリーの
投稿を表示したコードをかいたのですが
カテゴリーがない投稿ページだと
Fatal error: Uncaught Error: array_shift(): Argument #1 ($array) must be of type array, bool given
というエラーメッセージがでます
発生している問題・エラーメッセージ
Fatal error: Uncaught Error: array_shift(): Argument #1 ($array) must be of type array, bool given in
該当のソースコード
php
1<section id="sidebar"> 2 <section class="s-related"> 3 <div class="side-title">関連記事</div> 4 <ul> 5 <?php 6 $term = array_shift(get_the_terms($post->ID, 'blog_category')); 7 $args = [ 8 'post_type' => 'blog', 9 'posts_per_page' => 2, 10 'order' => 'Asc', 11 'taxonomy' => "blog_category", 12 'term' => $term->slug, 13 ]; 14 $pickup_query = new WP_Query($args); 15 ?> 16 17 <?php if ($pickup_query->have_posts()) : ?> 18 19 <?php while ($pickup_query->have_posts()) : $pickup_query->the_post(); ?> 20 21 22 <li> 23 <a href="<?php the_permalink(); ?>"> 24 <?php if (has_post_thumbnail()) : ?> 25 <?php the_post_thumbnail('blog'); ?> 26 <?php else : ?> 27 <img src=" <?php echo esc_url(get_theme_file_uri('img/noimage.png')); ?>"> 28 <?php endif; ?> 29 <div class="r-p"><?php the_title() ?></div> 30 </a> 31 32 </li> 33 34 <?php endwhile; ?> 35 36 37 <?php wp_reset_postdata(); ?> 38 </ul> 39 40 <?php else : ?> 41 <!-- 投稿が無い場合の内容 --> 42 43 <h1>投稿無し</h1> 44 <?php endif; ?> 45 46 </ul> 47 </section> 48 49 50 <section class="s-category"> 51 <div class="side-title">カテゴリー</div> 52 <ul> 53 <?php 54 $categories = get_categories($args); 55 foreach($categories as $category){ 56 echo '<li><a href="' . get_category_link($category -> term_id) . '">' . $category -> name; '</a><li>'; 57 58 } 59 ?> 60 </ul> 61 </section> 62</section>
試したこと
is_taxとif構文による条件分岐や
もとのコードにあるelseの編集などしましたがわからず
ググってもわかりませんでした
。
?
エラーメッセージの後半が省略されているようですが、どの箇所でエラーが出るのでしょうか。
6行目の部分です、回答の方でいただいた内容から無事に解決しました
ありがとうございます
ちゃんとヒントをあたえてもらえて、解決にみちびけたので
丸投げじゃないと理解して本当にありがとうございました。
'''php
<?php
// ↓ タームの情報を取得する
$tarms = get_the_terms( $post ->ID, 'blog_category' );
// ↓取得したデータが配列かの判定
if (is_array($tarms)) {
// ↓$tarms に配列データが入っていた場合
$term = array_shift(get_the_terms($post->ID, 'blog_category'));
$args = [
'post_type' => 'blog',
'posts_per_page' => 2,
'order' => 'Asc',
'taxonomy' => "blog_category",
'term' => $term->slug,
];
$pickup_query = new WP_Query($args);
}
else
{
// ↓$tarms に配列データが入ってない場合の処理
$args = [
'post_type' => 'not',
'taxonomy' => "not",
'term' => "not",
];
$pickup_query = new WP_Query($args);
}
?>
'''
回答1件
あなたの回答
tips
プレビュー