get_category_by_path

函数
get_category_by_path ( $category_path, $full_match = true, $output = OBJECT )
参数
  • (string) $category_path URL containing category slugs.
    Required:
  • (bool) $full_match Optional. Whether full path should be matched.
    Required:
    Default: true
  • (string) $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to a WP_Term object, an associative array, or a numeric array, respectively. Default OBJECT.
    Required:
    Default: OBJECT
返回值
  • (WP_Term|array|WP_Error|null) Type is based on $output value.
定义位置
相关方法
get_category_parentsget_category_by_slugget_site_by_pathget_category_templateget_page_by_path
引入
2.1.0
弃用
-

get_category_by_path: 这个函数通过路径检索一个类别对象。它需要一个参数:$category_path,它是类别的路径,例如”parent-category/child-category/grandchild-category”。

根据包含类别lug的URL检索一个类别。

将$category_path参数分解开来,以获得类别的slug。

试图找到子路径并将其返回。如果它没有找到一个匹配的,那么它将返回第一个匹配的类别lug,如果$full_match,被设置为false。如果它没有,那么它将返回null。

它也有可能在失败时返回一个WP_Error对象。在使用这个函数时,请检查一下。

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(
		array(
			'taxonomy' => 'category',
			'get'      => 'all',
			'slug'     => $leaf_path,
		)
	);

	if ( empty( $categories ) ) {
		return;
	}

	foreach ( $categories as $category ) {
		$path        = '/' . $leaf_path;
		$curcategory = $category;
		while ( ( 0 != $curcategory->parent ) && ( $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;
	}
}

常见问题

FAQs
查看更多 >