wordpress获取自定义文章类型分类
时间 : 2024-04-08 10:38:03声明: : 文章内容来自网络,不保证准确性,请自行甄别信息有效性

最佳答案

在WordPress中,可以使用函数`get_the_terms()`来获取自定义文章类型(Custom Post Type)的分类。确保你已经创建了自定义文章类型并为其定义了分类(taxonomy)。假设我们有一个名为“books”的自定义文章类型,并且有一个名为“genre”的分类法用于对书籍进行分类。

要获取自定义文章类型“books”中的特定文章的分类,可以使用如下代码:

```php

$terms = get_the_terms( get_the_ID(), 'genre' );

if ( $terms && ! is_wp_error( $terms ) ) {

$terms_list = array();

foreach ( $terms as $term ) {

$terms_list[] = $term->name;

}

echo implode( ', ', $terms_list );

}

上面的代码首先使用`get_the_terms()`函数来获取当前文章的分类,其中`get_the_ID()`用于获取当前文章的ID,`genre`是分类法的名称。接着,通过循环遍历每个分类项并将其名称存储在数组中,最后使用`implode()`函数将分类名称以逗号分隔的形式输出。

如果希望获取所有的分类而不仅仅是当前文章的分类,可以使用`get_the_terms()`函数的第二个参数来指定文章类型的ID。例如,要获取自定义文章类型“books”下所有文章的分类,可以使用如下代码:

```php

$posts = get_posts( array(

'post_type' => 'books',

'posts_per_page' => -1,

));

foreach ( $posts as $post ) {

$terms = get_the_terms( $post->ID, 'genre' );

if ( $terms && ! is_wp_error( $terms ) ) {

$terms_list = array();

foreach ( $terms as $term ) {

$terms_list[] = $term->name;

}

echo 'Book: ' . $post->post_title . ' - Genres: ' . implode( ', ', $terms_list ) . '<br>';

}

}

以上代码首先获取了所有自定义文章类型“books”的文章,并通过循环遍历每篇文章来获取其分类,并输出每本书的分类信息。

希望以上信息能够帮助到您获取WordPress中自定义文章类型的分类信息。

其他答案

要在WordPress中获取自定义文章类型的分类,首先需要确保已经创建了自定义文章类型(Custom Post Type)并为该类型设置了分类(Taxonomy)。接下来,可以通过以下代码来获取自定义文章类型的分类信息:

```php

// 获取特定自定义文章类型的分类

$taxonomy = 'your_taxonomy'; // 替换为实际的分类法名称

$post_type = 'your_custom_post_type'; // 替换为实际的自定义文章类型名称

$terms = get_the_terms($post->ID, $taxonomy);

if ($terms && !is_wp_error($terms)) {

$term_links = array();

foreach ($terms as $term) {

$term_links[] = '<a href="' . get_term_link($term->term_id, $taxonomy) . '">' . $term->name . '</a>';

}

echo '分类: ' . implode(', ', $term_links);

}

在上面的代码中,需要将`your_taxonomy`替换为实际的分类法名称,将`your_custom_post_type`替换为实际的自定义文章类型名称。这段代码可以放在自定义文章类型单篇文章模板文件(single-{post_type}.php)中,用于显示该文章所属的分类信息。

通过以上方法,就可以在WordPress中获取自定义文章类型的分类信息并显示在文章页面上,帮助用户更好地了解文章的分类信息。