Mapping Woocommerce order statuses using IF statements

Viewed 303

In Woocommerce, I am trying to map orders statuses with the following code:

function my_map_status ($status) {
    if ($status == "wc-processing") {
        return "WAA";
    } else {
        return $status;
    }
    if ($status == "wc-cancelled") {
        return "WAC";
    } else {
        return $status;
    }
}

But only the first one works.

How can I make it work for both?

2 Answers

The first IF ELSE statement is taking every possibility. Instead use an IF ELSEIF ELSE structure:

function my_map_status ($status) {
    if ($status == "wc-processing") {
        return "WAA";
    } elseif ($status == "wc-cancelled") {
        return "WAC";
    } else {
        return $status;
    }
}

It should better work.

The reason it's not getting beyond the first if is that it has an else that just returns - so, if you think it through logically you will see that if $status is not wc-processing then return (and quit function) - in other words, it never gets beyond the first if.

Instead, you might like to consider using switch/case, which makes for much easier reading than multiple if/elseifs, like this:

switch ( $status ) {
    case "wc-processing":
        return "WAA";
        break;
    case "wc-cancelled":
        return "WAC";
        break;
    default:
        return $status;
}

(in case you're wondering about the break - although not strictly necessary in this case (as the function will be exited with the return) it is good practice IMHO to always remember to use it every time you write a switch structure. More info on the page below.)

Further reading: http://php.net/manual/en/control-structures.switch.php

Related