Can someone tell me what this line does

Hi - working on moving some existing code in a site. Please forgive the PHP newbie question. I have this function:

function cc_remove_cpt_slug( $post_link, $post, $leavename ) {
  if(in_array($post->post_type, array('toronto','calgary','edmonton','halifax')) ) {
    $post_type = $post->post_type == 'toronto' ? 'toronto' : $post->post_type;
    $post_link = str_replace( '/' . $post_type . '/', '/', $post_link );
    return $post_link;
  } else {
    return $post_link;
add_filter( 'post_type_link', 'cc_remove_cpt_slug', 10, 3 );

Can someone please explain what line 3 does?

$post_type = $post->post_type == ‘toronto’ ? ‘toronto’ : $post->post_type;


$post is an OBJECT. $post->post_type is a part of the object.
The second line checks if the post_type is in the array of the four cities.
The third line sets the post_type in the $post OBJECT to ‘toronto’ OR leaves it set to the current value.
It is basically a shorthand version of a full compare. The following two examples are exactly the same…

$post_type = ( $post->post_type == 'toronto' ) ? 'toronto' : $post->post_type;

if ( $post->post_type == 'toronto' ) {
   $post->post_type = 'toronto';
} else {
   $post->post_type = $post->post_type;

*** Note, this is very odd code. It basically checks if checks for four different cities using an array. Then, if it does exist in the array, it changes the city to either ‘toronto’ or whatever was in it to start. I think it is trying to remove all the other 3 from the list. It basically makes the result ‘toronto’ if it is any of the four cities. For some reason the previous programmer wanted those four cities to be lumped into just the Toronto city. Hope this helps…

The line below:

$post_type = $post->post_type == ‘toronto’ ? ‘toronto’ : $post->post_type;

checks: if the class variable “post_type” has the value “toronto”, then it assigns “toronto” to the $post_type variable. Otherwise it takes whatever is in the class variable.

This check seems to be redundant and if anything, seems like a leftover from code refactorization and developer laziness. It could easily be shortened simply to:

$post_type = $post->post_type

Or even remove the $post_type variable completely and just end with:

str_replace( '/' . $post->post_type . '/', '/', $post_link );

1 Like

Thank you both for your help!

Sponsor our Newsletter | Privacy Policy | Terms of Service