Last active
December 21, 2023 08:50
-
-
Save lucymtc/e3b1cae75970599233eda55b65c2cecf to your computer and use it in GitHub Desktop.
is_tax_rest_request() The WordPress REST API workaround for is_tax()
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
/** | |
* Determine if it's a REST API request. | |
* | |
* @return boolean True if rest request. | |
*/ | |
function is_rest() { | |
return defined( 'REST_REQUEST' ) && REST_REQUEST; | |
} | |
/** | |
* Equivalent to is_tax() WP core function for the REST API | |
* Verifies if REST request and checks URI against available taxonomies. | |
* | |
* @return boolean|\WP_term; | |
*/ | |
function is_tax_rest_request() { | |
if ( ! is_rest() ) { | |
return false; | |
} | |
$request_uri = filter_input( INPUT_SERVER, 'REQUEST_URI', FILTER_SANITIZE_URL ); | |
$taxonomies = get_taxonomies( | |
[ | |
'public' => true, | |
'show_in_rest' => true, | |
] | |
); | |
// Capture the endpoint and slug value from request URI. | |
$pattern = '/\/wp-json\/wp\/v2\/(?<endpoint>\w+)\?.*?slug=(?<slug>[^&\s]+)/'; | |
preg_match( $pattern, $request_uri, $matches ); | |
if ( empty( $matches ) || ! in_array( $matches['endpoint'], $taxonomies, true ) ) { | |
return false; | |
} | |
$taxonomy = $matches['endpoint']; | |
$term = get_term_by( 'slug', $matches['slug'], $taxonomy ); | |
if ( ! $term instanceof \WP_Term ) { | |
return false; | |
} | |
return $term; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment