Last active
March 9, 2023 17:03
-
-
Save morgyface/f390f96b6c1007e8ce1b74b2fb652644 to your computer and use it in GitHub Desktop.
WordPress | Extract a taxonomy term from the referring URL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 viakind/models
you'd see model pictures and her actual name.It's used like this:
The two main components of the function are wp_get_referer and parse_url.