0

SOLVED (Credits will be added in 10 min.)

I have a custom post type script in my functions.php (Wordpress) of which I do not understand its meaning.

$query_args = array(
'posts_per_page' => 5,
'post_type'      => $is_some_page ? CPT_ONE : CPT_TWO,
'post_status'    => 'publish',
'paged'          => 1
);

The script is loading perfect, no problems there.

Problem: I would like to add an additional post_type but I don't understand the : symbol... What is its meaning? And how to add more? This doesn't work:

'post_type' => $is_some_page ? CPT_ONE : CPT_TWO : CPT_THREE,

EDIT: Thanks for having a look and changing the labels for the question. Many thanks to everybody else for pointing me in the right direction with the operators.

Ruud
  • 249
  • 2
  • 8
  • 22

1 Answers1

5

What you are looking at is the ternary if operator (a lot of languages have this, including both PHP and Javascript).

So this:

$someVar = $someBool ? $val1 : $ val2

is equivalent to:

if ($someBool)
{
    $someVar = $val1;
}
else
{
    $someVar = $val2;
}

So this:

'post_type' => $is_some_page ? CPT_ONE : CPT_TWO : CPT_THREE

doesn't make sense because $is_some_page can only evaluate as true or false. But it's not clear what your logic should be. Under what situation do you want post_type to be CPT_ONE, CPT_TWO or CPT_THREE?

You could do something like this:

'post_type' => $is_some_page ? CPT_ONE : ($some_other_condition ? CPT_TWO : CPT_THREE)

Which is equivalent to an if / else if / else

Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43
Matt Burland
  • 44,552
  • 18
  • 99
  • 171
  • Please watch out in your ternary condition. PHP's ternary operator works right-to-left (unless told to otherwise by parenthesises), so it doesn't do what you'd expect: http://codepad.org/o3tgL4Lw – h2ooooooo Mar 06 '14 at 17:22
  • 1
    It can also give [very very odd results](http://codepad.org/gTprxKHX). Eg: `var_dump(true ? 1 : false ? 2 : 3);` prints `int(2)` while `var_dump(true ? 1 : (false ? 2 : 3));` prints `int(1)`. – h2ooooooo Mar 06 '14 at 17:27
  • @h2ooooooo: Ugh, PHP. So short version is probably avoid nesting ternary operators in PHP because it's PHP. – Matt Burland Mar 06 '14 at 18:59
  • @MattBurland Yeah exactly. Apparently PHP reads it as `var_dump((true ? 1 : false) ? 2 : 3)`. – h2ooooooo Mar 06 '14 at 19:03