• Hey guys on my wordpress blog I am trying to compare the following

    if ($category[0]->cat_name == “television” )

    in wordpress the $category[] is the array of categories a post has, and cat-name i just the actual name of that category.

    If I echo $category[0]->cat_name it is television

    but I can’t get this to flag as true for the if statement, something is wrong and it keeps doing the ELSE part.

    Anyone know what is wrong here?

    thank you alot for any help

    Travis

Viewing 3 replies - 1 through 3 (of 3 total)
  • I can’t remember the specifics of why, but I ran into this myself. I didn’t try it, but you can try using the identity operator ‘===’ instead of just ‘==’. I think it has something to do with instances and values of objects. I’m not real familiar with OOP yet myself.

    What I did is assigned the instance of the object to a variable then ran the comparison on it.

    $varcheck = $category[0]->cat_name
    
    if ($varcheck=="television") {
     do this
    }
    else {
     do that
    }

    Are you looping through the categories? Or, just trying to check the first category?

    It might be better to check against the slug or ID rather than the name. I’ve had trouble with category names in certain cases before and have found that both the slug and ID work better.

    Slug:

    if ( $category[0]->slug == 'television' )

    ID:

    if ( $category[0]->term_id == 5 ) /* Change 5 to ID of category */
    Thread Starter phaze112

    (@phaze112)

    thank you guys.

    Green yea good point in coding better to go with prob the ID.

    it was the fact I was missing:

    $category = get_the_category();

    Before trying to use the category[] array.

    I tested in sample code and got the output with an echo just forgot to move up the $category = get_the_category(); part ??

    thank you all!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘PHP If Else – String Comparison Question’ is closed to new replies.