【WordPressエラー】「Warning: Undefined variable $post in …」「Warning: Attempt to read property “ID” on null in …」

PHP7.3からPHP8.0に変更がありWordPressでエラーメッセージが発生しました。

表題のエラーがPHP8.0より通知ではなく、独立エラーとして扱われるようになった為です

エラー内容

「get_the_terms」記事に基づくタクソノミーの取得のための下記の記述でエラー発生

<?php 
$terms = get_the_terms($post->ID, 'tag-workshop');
if ($terms) {
foreach ($terms as $term) {
echo '<a class="tagc-tag-workshop" tag-id="' . $term->term_id . '" href="' . get_permalink() . '">' . $term->name . '</a>';
}
?>

Warning: Undefined variable $post in …

Warning: Attempt to read property “ID” on null in …

(解決策)変数を定義する

Undefined variable $postとは変数の未定義によるエラーです

global $post;を追記することによりエラー解消しました

<?php 
global $post;
$terms = get_the_terms($post->ID, 'tag-workshop');
if ($terms) {
foreach ($terms as $term) {
echo '<a class="tagc-tag-workshop" tag-id="' . $term->term_id . '" href="' . get_permalink() . '">' . $term->name . '</a>';
}
?>

参考サイト

【PHP7から8へ切替】Warning: Undefined variableが表示された場合の修正方法
https://it-column.mjeinc.co.jp/archives/3513

WordPressのグローバル変数「$post」とは?中身や使い方について解説
https://tcd-theme.com/2024/01/wp-post-object.html

PHP8.0でWordPressの「Attempt to read property “ID” on null」のエラーを解決したい
https://ja.stackoverflow.com/questions/85387/php8-0%e3%81%a7wordpress%e3%81%ae-attempt-to-read-property-id-on-null-%e3%81%ae%e3%82%a8%e3%83%a9%e3%83%bc%e3%82%92%e8%a7%a3%e6%b1%ba%e3%81%97%e3%81%9f%e3%81%84