• Resolved rinchent

    (@rinchent)


    I’m currently trying to use a ternary operator as I’m using echo.

    I’m trying to check if a category ID equals the number 3, if it does, I would like it to create a new div containing an image.

    This is the ternary operator i’m using which is inside a for loop:
    `<p>’. wp_get_post_categories($recent[“ID”])[0] == “3” ? “yes” : “no”.'</p>

    Outputting just wp_get_post_categories($recent[“ID”])[0] gets me the number “3”, although “no” always seems to appear. I’ve tried using == 3 as well but still no luck.
    In addition to this, everything inside the loop which generates UI styling disappears.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    wp_get_post_categories() by default returns an array of term objects, not just IDs.
    Try this: wp_get_post_categories($recent[“ID”])[0]->term_id == 3

    IMO, complex statements as a ternary condition make code hard to read. In this case I personally would assign the term ID to a variable, then use that in the ternary condition. 3 == $term_id ? "yes" : "no" Much more readable! Not as efficient, but this is not going to ruin you page load speed. Just sayin’. Do as you please ??

    Thread Starter rinchent

    (@rinchent)

    Hey thanks for the suggestion.

    I’ve done what you said and assigned it as term_id, good news is that the UI doesn’t disappear anymore – styling is still a bit off but that’s easily fixable.

    However, it’s still showing false when checking if $term_id equals to 3. Tried to use strcmp as well but no luck!

    Edit: Just done var_dump($term_id == 3) and it’s showing the the values correctly, no idea why the original method isn’t working!

    • This reply was modified 7 years, 9 months ago by rinchent.
    Thread Starter rinchent

    (@rinchent)

    So i’ve just realised I can do everything outside of the echo and just print off a variable with the result inside the echo.

    Closing this now, thanks for your help!!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Ternary Operator not showing correct data + removing UI’ is closed to new replies.