Created
June 20, 2016 19:29
-
-
Save stevenslack/38bc16b6a1ed1f9eb7b6f25b80890de7 to your computer and use it in GitHub Desktop.
Get terms from a URL
This file contains 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 | |
/** | |
* Get term object from URL | |
* | |
* Assumes the URL structure follows a standard pretty permalink eg: domain/taxonomy/term/ | |
* | |
* @param string $url The URL to search for a term slug | |
* @param string $taxonomy_name specify a taxonomy in which the term resides | |
* @return object The term object | |
*/ | |
function get_term_from_url( $url, $taxonomy_name ) { | |
if ( ! taxonomy_exists( $taxonomy_name ) ) { | |
return false; | |
} | |
$cache_key = md5( serialize( $url . $taxonomy_name ) ); | |
$output_term = wp_cache_get( $cache_key, '', true ); | |
if ( false === $output_term ) { | |
$taxonomy = get_taxonomy( $taxonomy_name ); | |
// first check rewrite slug and then fallback to taxonomy name | |
if ( isset( $taxonomy->rewrite['slug'] ) ) { | |
$taxonomy_slug = $taxonomy->rewrite['slug']; | |
} elseif ( isset( $taxonomy->name ) ) { | |
$taxonomy_slug = $taxonomy->name; | |
} else { | |
return false; | |
} | |
$path = parse_url( $url, PHP_URL_PATH ); | |
// match the taxonomy slug in the URL and grab the trailing term slug to isolate the term | |
if ( false !== preg_match( "/(\/({$taxonomy_slug})\/)/i", $path ) ) { | |
$term_slug = basename( untrailingslashit( ltrim( $path, "/{$taxonomy_slug}/" ) ) ); | |
if ( term_exists( $term_slug ) ) { | |
$term = get_term_by( 'slug', $term_slug, $taxonomy->name ); | |
if ( null !== $term && ! is_wp_error( $term ) ) { | |
$output_term = $term; | |
} | |
} | |
} | |
wp_cache_set( $cache_key, $output_term, 'terms_from_url' ); | |
} | |
return $output_term; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment