Skip to content

Instantly share code, notes, and snippets.

@morgyface
Last active March 9, 2023 17:03
Show Gist options
  • Save morgyface/f390f96b6c1007e8ce1b74b2fb652644 to your computer and use it in GitHub Desktop.
Save morgyface/f390f96b6c1007e8ce1b74b2fb652644 to your computer and use it in GitHub Desktop.
WordPress | Extract a taxonomy term from the referring URL
<?php
function referer_term( $taxonomy ) {
$term = null;
$referer = wp_get_referer(); // Get the referer URL
if( $referer ) {
// Here we parse the URL extracting the path element of it
$referer_path = parse_url( $referer, PHP_URL_PATH );
if( $referer_path && $taxonomy ) {
// If we have a path and a taxonomy we are good to go
if ( strpos( $referer_path, $taxonomy ) !== false ) {
// If the string contains the taxonomy we now need to get the term
$term = substr( $referer_path, strpos( $referer_path, $taxonomy ) + strlen( $taxonomy ) ); // Get everything after the taxonomy
$term = trim( $term, '/' ); // Trim off the slashes
}
}
}
return $term;
}
@morgyface
Copy link
Author

I created this as I had posts which contained context specific content. If the posts were reached via an archive, I was able to use this function to display content in single.php that was relevant.

An example was an actress and model called Betty Smith, when you accessed her post via kind/actors her acting name (Elizabeth Smith) was displayed and a gallery of acting pictures. Whilst via kind/models you'd see model pictures and her actual name.

It's used like this:

if ( referer_term( 'kind' ) == 'models' )  {
    // Show modelling content
}

The two main components of the function are wp_get_referer and parse_url.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment