Why isn't my if statement working with get_the_category?

后端 未结 2 1996
小蘑菇
小蘑菇 2021-01-26 00:00

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

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-26 00:19

    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.

提交回复
热议问题