WordPress主题使用自定义分类法(taxonomy)可以让您更好地组织和分类化您的内容。以下是创建和使用自定义分类法的步骤:
functions.php
文件中添加以下代码创建一个自定义分类法,例如"书籍类型(book_type)":function custom_taxonomy() {
$labels = array(
'name' => _x( '书籍类型', 'taxonomy general name' ),
'singular_name' => _x( '书籍类型', 'taxonomy singular name' ),
'search_items' => __( '搜索书籍类型' ),
'popular_items' => __( '热门书籍类型' ),
'all_items' => __( '所有书籍类型' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( '编辑书籍类型' ),
'update_item' => __( '更新书籍类型' ),
'add_new_item' => __( '添加新书籍类型' ),
'new_item_name' => __( '新书籍类型名称' ),
'separate_items_with_commas' => __( '用逗号分隔多个书籍类型' ),
'add_or_remove_items' => __( '添加或移除书籍类型' ),
'choose_from_most_used' => __( '从最常用的中选择书籍类型' ),
'not_found' => __( '未找到书籍类型' ),
'menu_name' => __( '书籍类型' ),
);
$args = array(
'hierarchical' => false, // 设置为false以使该分类法类似于标签(non-hierarchical),而不是类别(hierarchical)
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'update_count_callback' => '_update_post_term_count',
'query_var' => true,
'rewrite' => array( 'slug' => 'book_type' ), // 分类法的URL重写,如:https://example.com/book_type/book1
);
register_taxonomy( 'book_type', array( 'post' ), $args ); // 将分类法应用于文章(post)类型
}
add_action( 'init', 'custom_taxonomy', 0 );
在文章中应用自定义分类法:
显示文章的自定义分类法:
$terms = get_the_terms( get_the_ID(), 'book_type' ); // 获取文章的"书籍类型"分类法项
if ( $terms ) {
foreach ( $terms as $term ) {
echo '<a href="' . get_term_link( $term ) . '">' . $term->name . '</a>';
}
}
这将输出一个链接,其中包含文章的"书籍类型"分类法项的名称,并将链接到该分类法的存档页面。
希望这些代码和说明对您有所帮助!