How to know which category or term you came from in WordPress

I’ve come across projects where the client wanted to do something base on where you came from. So this example will check to see which category or taxonomy term you came from and show a category or term menu based off where you came from.

First start with the link from a taxonomy page. We add the “?cat= and echo the term_id to the permalink url.

<?php 
$queried_object = get_queried_object(); 
$taxonomy = $queried_object->taxonomy;
?>

<li>
 <a href="<?php the_permalink();?>?cat=<?php echo $queried_object->term_id ?>">
   <?php echo $queried_object->name ?>
 </a>
</li>

Once we’ve clicked through, we get that id, find the parent term so we can list it’s name.

<?php
  // Get term id value from incoming URL.
  $taxonomy = 'portcats';
  $term_id = $_REQUEST['cat'];
  //get the parent
  $child_term = get_term( $term_id, $taxonomy );
  $parent_term = get_term( $child_term->parent, $taxonomy );

?>

<h1 class="page-title">
<?php 
$url = get_bloginfo('url');
?>
	<?php echo $parent_term->name ?> | 
    <a href="<?php echo $url . '/portfolio-categories/' . $parent_term->slug ?>/#viewall">
    	View All
    </a>
</h1>