根据包含类别slug的URL检索类别。

原型

get_category_by_path( string $category_path, bool $full_match = true, string $output = OBJECT )

描述

打破$ category_path参数以获取类别slug。

参数

$category_path (string) (Required) 包含类别slugs的URL。

$full_match (bool) (Optional)  是否应匹配完整路径。

$output (string) (Optional)  所需的返回类型。 OBJECT,ARRAY_A或ARRAY_N之一,分别对应于WP_Term对象,关联数组或数值数组。

返回值

(WP_Term|array|WP_Error|null)  类型基于$输出值。

源文件

路径:wp-includes/category.php

<?php
...
function get_category_by_path( $category_path, $full_match = true, $output = OBJECT ) {
	$category_path = rawurlencode( urldecode( $category_path ) );
	$category_path = str_replace( '%2F', '/', $category_path );
	$category_path = str_replace( '%20', ' ', $category_path );
	$category_paths = '/' . trim( $category_path, '/' );
	$leaf_path  = sanitize_title( basename( $category_paths ) );
	$category_paths = explode( '/', $category_paths );
	$full_path = '';
	foreach ( (array) $category_paths as $pathdir ) {
		$full_path .= ( $pathdir != '' ? '/' : '' ) . sanitize_title( $pathdir );
	}
	$categories = get_terms( 'category', array('get' => 'all', 'slug' => $leaf_path) );
	if ( empty( $categories ) ) {
		return;
	}
	foreach ( $categories as $category ) {
		$path = '/' . $leaf_path;
		$curcategory = $category;
		while ( ( $curcategory->parent != 0 ) && ( $curcategory->parent != $curcategory->term_id ) ) {
			$curcategory = get_term( $curcategory->parent, 'category' );
			if ( is_wp_error( $curcategory ) ) {
				return $curcategory;
			}
			$path = '/' . $curcategory->slug . $path;
		}
		if ( $path == $full_path ) {
			$category = get_term( $category->term_id, 'category', $output );
			_make_cat_compat( $category );
			return $category;
		}
	}
	// If full matching is not required, return the first cat that matches the leaf.
	if ( ! $full_match ) {
		$category = get_term( reset( $categories )->term_id, 'category', $output );
		_make_cat_compat( $category );
		return $category;
	}
}
...
?>

其他

英文文档:https://developer.wordpress.org/reference/functions/get_category_by_path/