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";
}
but the result is the C_News after every post category even if it's not the right category.
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";
}
Your code (if ($category_detail = "COMPANY NEWS")
) is always true as it is an assignment, therefore it will always echo the COMPANY NEWS
branch.
The only issue I can see is that you need to use a comparison operator ("==") instead of setting the $category_detail variable with ("="). Make sure you're changing that in BOTH places.
Also note that the wordpress coding standards say your comparison should have the variable on the right, that way if you ever mis-type it or something else goes wonky the operation fails and throws an error instead of ALWAYS returning true.
Example:
if( "Company News" == $category_detail ){
echo "hello world";
}