stevenslack
6/20/2016 - 7:29 PM

Get terms from a URL

Get terms from a URL

<?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;
}