4

WordPress recently depreciated wp_get_sites() in favor of get_sites() in version 4.6. I've seen a few updates where people are pushing out changes to their code by simply switching it from wp_get_sites() to get_sites(). However, I noticed this one today:

$sites = wp_get_sites();

foreach ( $sites as $site ) {
...

to

$sites = ( function_exists( 'get_sites' ) ) ? get_sites() : wp_get_sites();

foreach ( $sites as $site ) {
$site = (array) $site;
...

What does this change do and why would it be useful over removing wp_ from the old function to use the new one? How does it work?

Where can I learn more about using the shortened version where it checks for the function and has a fallback all in one line? Is there a name for this?

5

This is a great question.

First of all, the comparison operator (?:) you're referring to is called a ternary operator. It's great for simple if/then blocks. It took me a while to get used to them, but now I use them all the time.

You can take a simple expression and return a value depending on the result of that expression.

This will put the sanitized value of $_GET['string'] into the variable if it exists, and an empty string if it does not.

$query_string = isset($_GET['string']) ? sanitize_text_field($_GET['string']) : '';

You can also echo this directly

echo $name != '' && isset($name) ? "Hello, " . $name : "I don't believe we've met"

Or put it in an array... and with booleans!

$my_array = array(
    'is_gt_5' => $this_number > 5 ? true : false
);

Why use them here?

The reason someone might use a fallback is because not everyone is on 4.6 yet. Writing it this way helps maintain backward and support future compatibility.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.