为什么我的 if 语句不适用于 get_the_category? [英] Why isn't my if statement working with get_the_category?
问题描述
我正在尝试创建一个 if 语句,该语句将为帖子所在的每个类别回显一个单词,它从帖子 ID 中获取类别名称,但第一个类别是所有故事,因此我要求它获取第二个类别帖子所在的位置:
Im trying to make an if statement that would echo a word for each category that the post is in, it gets the category name from the post id, but the first category is All Stories so I asked it to get the second category that the post is in:
$category_detail=get_the_category( $post->ID )[1]->name;
echo $category_detail;
// echoes COMPANY NEWS
if($category_detail == "COMPANY NEWS") {
echo "C_News";
} elseif ($category_detail == "SECTOR OPPORTUNITIES") {
echo "S_News";
}
但结果是每个帖子类别之后的 C_News,即使它不是正确的类别.
but the result is the C_News after every post category even if it's not the right category.
我尝试使用 is_category( 'Company News' ) 但这不起作用,任何建议将不胜感激.
I tried using is_category( 'Company News' ) but that didn't work, any suggestions would be greatly appreciated.
推荐答案
您正在寻找比较(==
)而不是分配强> (=
):
You are looking for a comparison (==
) instead of an assignment (=
):
$category_detail=get_the_category( $post->ID )[1]->name;
echo $category_detail;
// echoes COMPANY NEWS
if($category_detail == "COMPANY NEWS") {
echo "C_News";
} elseif ($category_detail == "SECTOR NEWS") {
echo "S_News";
}
您的代码 (if ($category_detail = "COMPANY NEWS")
) 始终为真,因为它是一个分配,因此它始终与 COMPANY 相呼应NEWS
分支.
Your code (if ($category_detail = "COMPANY NEWS")
) is always true as it is an assignment, therefore it will always echo the COMPANY NEWS
branch.
这篇关于为什么我的 if 语句不适用于 get_the_category?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!