首页 > SEO优化 > wordpress教程:面包屑导航(更细版本)

wordpress教程:面包屑导航(更细版本)

时间:2023年10月17日 分类:SEO优化 浏览量:79

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

  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.  }

  13.  $path[] = wpmomo_breadcrumb_output( get_category_link( $category->term_id ), $category->name);

  14.  $cats_id[] = $category->term_id;

  15.  }

  16.  }

  17.  }

  18.  }

  19.  if( is_singular() && !is_single() && !is_page() ){

  20.  $post_type = get_post_type();

  21.  $post_type_obj = get_post_type_object( $post_type );

  22.  $path[] = wpmomo_breadcrumb_output( get_post_type_archive_link( $post_type ), $post_type_obj->labels->singular_name);

  23.  }

  24.  $path[] = wpmomo_breadcrumb_output( get_permalink($post_id), get_the_title($post_id));

  25.  echo join( $separator ,$path);

  26.  }

  27.  function wpmomo_get_category_parents( $id, $separator=”, $visited = array() ) {

  28.  $chain = ”;

  29.  $parent = get_term( $id, ‘category’ );

  30.  if ( is_wp_error( $parent ) )

  31.  return $parent;

  32.  $name = $parent->name;

  33.  if ( $parent->parent && ( $parent->parent != $parent->term_id ) && !in_array( $parent->parent, $visited ) ) {

  34.  $visited[] = $parent->parent;

  35.  $chain .= wpmomo_get_category_parents( $parent->parent, $separator, $visited );

  36.  }

  37.  $chain .= wpmomo_breadcrumb_output( get_category_link( $parent->term_id ), $name);

  38.  return $chain;

  39.  }

  40. function wpmomo_breadcrumb_output($url,$name){

  41.  return ‘<span”>’.$name.”;

  42.  }

代码放进去后,下面就是在你的前端位置加入调用了,代码如下:

  1. <?php wpmomo_breadcrumb_html(get_the_ID(),’&nbsp› &nbsp’); ?>

觉得文章有用就打赏一下文章作者

微信扫一扫打赏

标签: