之前大叔分享过一例 WordPress 面包屑 的代码教程,详情可见:GO  今天再分享一款更加细化的 WordPress 面包屑导航,教程依然很简单,往 functions.php 加代码,然后前端调用即可,至于样式,自由发挥吧。代码如下:

breadcrumb

  1. function wpmomo_breadcrumb_html($post_id,$separator){
  2. $path[] = wpmomo_breadcrumb_output( home_url('/'), '首页');
  3.  if( get_post_type($post_id)=='post' ) {
  4. $cats_id = array();
  5.  $categories = get_the_category($post_id);
  6. if($categories){
  7.  foreach($categories as $category) {
  8. if(!in_array($category->term_id,$cats_id)){
  9.  if ( $category->parent ){
  10. $path[] = wpmomo_get_category_parents( $category->parent, $separator );
  11.  $cats_id[] = $category->parent;
  12.  $path[] = wpmomo_breadcrumb_output( get_category_link( $category->term_id ), $category->name);
  13. $cats_id[] = $category->term_id;
  14.  }
  15.  }
  16.  if( is_singular() && !is_single() && !is_page() ){
  17. $post_type = get_post_type();
  18.  $post_type_obj = get_post_type_object( $post_type );
  19. $path[] = wpmomo_breadcrumb_output( get_post_type_archive_link( $post_type ), $post_type_obj->labels->singular_name);
  20.  }
  21. $path[] = wpmomo_breadcrumb_output( get_permalink($post_id), get_the_title($post_id));
  22.  echo join( $separator ,$path);
  23.  function wpmomo_get_category_parents( $id$separator=''$visited = array() ) {
  24. $chain = '';
  25.  $parent = get_term( $id, 'category' );
  26. if ( is_wp_error( $parent ) )
  27.  return $parent;
  28. $name = $parent->name;
  29.  if ( $parent->parent && ( $parent->parent != $parent->term_id ) && !in_array( $parent->parent, $visited ) ) {
  30. $visited[] = $parent->parent;
  31.  $chain .= wpmomo_get_category_parents( $parent->parent, $separator$visited );
  32.  $chain .= wpmomo_breadcrumb_output( get_category_link( $parent->term_id ), $name);
  33. return $chain;
  34.  }
  35. function wpmomo_breadcrumb_output($url,$name){
  36.  return '<span">'.$name.'';
    1. <?php wpmomo_breadcrumb_html(get_the_ID(),'&nbsp› &nbsp'); ?>