$item->term_id, 'url' => get_term_link($item->term_id, 'product_cat'), ]; }, get_terms(['taxonomy' => 'product_cat'])); foreach ($matches as $key => $value) { // Replace the temporary id with the category id. $newCode = preg_replace( '/' . preg_quote($value[0], '/') . '/', str_replace($value[1], $categories[$key]['id'], $value[0]), $newCode, 1 ); // Replace the temporary placeholder URL with the actual category URL. $newCode = preg_replace( '/' . preg_quote('http://patterns.test/?product_cat=accessories', '/') . '/', $categories[$key]['url'], $newCode, 1 ); } return $newCode; } }