php conditional statement: not equal to operator

2019-09-07 23:58发布

I am trying to do the following with wordpress:

"If is NOT page 92, OR page parent is NOT 92."

Here is what I have:

<?php if (!is_page(92) || $post->post_parent !== 92) { echo $foo; } ?>

If I use one or the other as condition, it works; When I add the second condition, it breaks.

Any help would be well appreciated.

Cheers!

3条回答
Juvenile、少年°
2楼-- · 2019-09-08 00:13

Your problem is probably in using || instead of &&.

You want it to echo if you are not on page 92 AND you are not in a subpage of page 92.

Let's say you're on page 92, then your current code does this:

if (false || true)

because 92 is not a parent of page 92. Thus, since one condition is true, it triggers.

If you're on a subpage of 92, then it's the opposite:

if (true || false)

If you're on a page that isn't 92 or a subpage of 92, then you get:

if (true || true)

So, it will always trigger, regardless of what page your on, because || requires only a single true statement for the entire condition to be true.

Hence, change your code to

<?php if (!is_page(92) && $post->post_parent !== 92) { echo $foo; } ?>

Which gives a logical run down like:

Page 92:

if(false && true) //false, won't trigger

Subpage of 92:

if(true && false) //false, won't trigger

Some unrelated page:

if(true && true) //true, will trigger

查看更多
一夜七次
3楼-- · 2019-09-08 00:31

You have an additional equals sign in your statement. The operator !== is for boolean checks. Since post_parent will automatically resolve to "true" since it has a value, it will always echo "foo". Change it to the following.

<?php if (!is_page(92) || $post->post_parent != 92) { echo $foo; } ?>
查看更多
Emotional °昔
4楼-- · 2019-09-08 00:31

It's only != not !==, only one equal

查看更多
登录 后发表回答