如何在WordPress中获取类别和子类别

如何在WordPress中获取类别和子类别

如何在WordPress中获取类别和子类别

  在WordPress建站中,the_category() 模板函数常用于WordPress 主题开发中。它显示父类别和任何子类别。在某些情况下,此函数可能会生成一个长列表。当一个网站有大量的类别和子类别时,这个问题就变得很重要。

如何在WordPress中获取类别和子类别

  在这种 WordPress 获取类别的情况下,_catagory() 函数通常会创建一个巨大的列表,该列表通常对任务没有用处。本文,晓得博客为你介绍如何在WordPress中获取类别和子类别。

获取特定的帖子类别

  以下代码将获取特定帖子的类别。请注意,必须将此代码添加到content-single.phpsingle.php

<?php  $taxonomy = 'category'; 
// ID Gets which assign post 
$post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
 
// Links seprator.
$separator_link = ', ';
 
if ( ! empty( $post_terms ) && ! is_wp_error( $post_terms ) ) {
 
    $term_ids = implode( ',' , $post_terms );
 
    $terms = wp_list_categories( array(
        'title_li' => '',
        'style'    => 'none',
        'echo'     => false,
        'taxonomy' => $taxonomy,
        'include'  => $term_ids
    ) );
 
    $terms = rtrim( trim( str_replace( '<br />',  $separator_link, $terms ) ), $separator_link );
 
    // show category post.
    echo  $terms;
}  ?>

  推荐:(图文)BackupBuddy插件教程WordPress备份还原迁移插件教程

从父类别获取子类别

  从特定帖子的父类别中获取子类别。接下来,在索引和存档帖子循环开始的帖子模板中添加以下代码。也可以在标题后添加此代码。

<?php
$taxonomy = 'category';
// ID Gets which assign post 
$post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
$post_terms_specific = array (1);
$result_post=array_diff($post_terms, $post_terms_specific);
// Links seprator.
$separator = ', ';
if ( !empty( $result_post ) && !is_wp_error( $result_post ) ) {
 $term_ids = implode( ',' , $result_post);
 $terms = wp_list_categories( 'title_li=&style=none&echo=0&taxonomy=' . $taxonomy . '&include=' . $term_ids );
 $terms = rtrim( trim( str_replace( '', $separator, $terms ) ), $separator );
 // show category post.
 echo $terms;
}
?>

类别名称 按 ID 获取

<?php
//First Method
$id_name= '22';
echo get_the_category_by_ID($id_name);
//Second Method
echo get_cat_name(22);
?>

类别说明(通过 ID)

  类别 slug 是该类别的 URL 名称:

<?php

 $id_description = '22';
 echo category_description($id_description);

?>

  推荐:如何阻止WordPress垃圾评论

类别说明(通过 Slug 获取)

  类别 slug 是该类别的 URL 名称:

<?php

 echo category_description( get_category_by_slug('uncategorized')->term_id ); 

?>

  您可以使用 id 生成指向特定类别的链接。使用以下代码:

<?php
$id_link = '1';
$categorylink = get_category_link( $id_link );
echo esc_url($categorylink);
?>

总结

  以上事晓得博客为你介绍的如何在WordPress中获取类别和子类别的全部内容,讨论了如何获取特定的帖子类别、父类别的子类别、ID 的类别名称、ID 的类别描述和 ID 的类别链接。如果需要可发表评论。

  推荐:[已解决]如何修复WordPress中的您关注的链接已过期错误

给文章评分

Claude、Netflix、Midjourney、Chatgpt Plus账号购买,ChatGPT API购买,优惠码XDBK,用户购买的时候输入优惠码可以打95折

Chatgpt-Plus注册购买共享账号
Kinsta-free-hosting主机
Kinsta-free-hosting主机
Elementor可视化创建WordPress网站
Elementor可视化创建WordPress网站
滚动至顶部