[英]WordPress > Get custom taxonomy from a custom post type
1.如何顯示所有自定義帖子類型並在上方設置過濾器,其中類別可用作過濾器選項卡?
2.如何通過自定義分類“類別”和顯示鏈接在自定義模板中循環?
HTML 結構
自定義帖子類型 URL:/wp-admin/edit-tags.php?taxonomy=categories&post_type=products
PHP
<?php get_term( $term, $taxonomy, $output, $filter ) ?>
<?php
$args=array(
'name' => 'categories'
);
$output = 'products'; // or names
$taxonomies=get_taxonomies($args,$output);
if ($taxonomies) {
foreach ($taxonomies as $taxonomy ) {
echo '<p>' . $taxonomy->name . '</p>';
}
}
?>
<?php
$args = array(
'public' => true,
'_builtin' => false
);
$output = 'names'; // or objects
$operator = 'and'; // 'and' or 'or'
$taxonomies = get_taxonomies( $args, $output, $operator );
if ( $taxonomies ) {
foreach ( $taxonomies as $taxonomy ) {
echo '<p>' . $taxonomy . '</p>';
}
}
您可以這樣做以獲取自定義分類法的所有術語:
https://developer.wordpress.org/reference/functions/get_terms/
$terms = get_terms( array(
'taxonomy' => 'categories',
'hide_empty' => false,
) );
foreach ( $terms as $term ) {
$term_link = get_term_link( $term );
}
$term
返回一個具有以下結構的數組:
array(
[0] => WP_Term Object
(
[term_id] =>
[name] =>
[slug] =>
[term_group] =>
[term_taxonomy_id] =>
[taxonomy] =>
[description] =>
[parent] =>
[count] =>
[filter] =>
)
$term_link
將為您提供分類術語檔案的永久鏈接。
https://developer.wordpress.org/reference/functions/get_term_link/
關於如何實現過濾器選項卡的其他問題:查看此插件: https : //wordpress.org/plugins/beautiful-taxonomy-filters/
要查找與給定帖子類型相關的分類法,請使用 WordPress get_object_taxonomies()
函數,如下所示:
$taxonomies = get_object_taxonomies('post', 'objects');
$taxonomies
將是一組WP_Taxonomy
對象。 省略第二個參數以獲取 post_type slug 數組。
要通過自定義分類進行查詢,請創建一個新的 WP_Query,如下所示:
$args = [
'posts_per_page' => -1,
'tax_query' => [
[
'taxonomy' => 'categories',
'field' => 'slug',
'terms' => ['your-term'],
],
],
];
$filterQuery = new WP_Query($args);
雖然可以使用register_post_type
在 post_types 上聲明分類關聯,但關聯是可選的並且非常弱。 在內部,WordPress 采取另一種方式並將 post_types 分配給分類法。
每個分類法都有一個object_type
屬性,它是它所知道的 post_types 的 slug 數組。 深入研究register_post_type
源代碼,我們看到它為taxonomies
參數屬性中的每個項目調用register_taxonomy_for_object_type
,然后簡單地向分類法的object_type
數組添加一個 slug。 這是唯一一次使用 post_type 的分類屬性。 我更喜歡在注冊分類法時聲明 post_types,因為它更接近 WordPress 的工作方式,並且誤解了這種關聯在過去給我帶來了很多悲傷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.