首页 问答 正文

如何在WordPress中添加面包屑导航

注册会员 / 悠然自学 / 2023-06-11/ 浏览 156 次

WordPress中添加面包屑导航可以通过以下步骤实现:

  1. 在主题的functions.php文件中添加以下代码:
function get_breadcrumbs() {
  global $post;

  $output = '<ul>';

  if (!is_front_page()) {
    $output .= '<li><a href="' . home_url() . '">Home</a></li>';

    if (is_category() || is_single()) {
      $category = get_the_category();
      $cat_id = $category[0]->term_id;
      $output .= '<li><a href="' . get_category_link($cat_id) . '">' . $category[0]->cat_name . '</a></li>';

      if (is_single()) {
        $output .= '<li>' . get_the_title() . '</li>';
      }
    } elseif (is_page()) {
      $ancestors = get_post_ancestors($post);

      if ($ancestors) {
        $ancestors = array_reverse($ancestors);

        foreach ($ancestors as $ancestor) {
          $output .= '<li><a href="' . get_permalink($ancestor) . '">' . get_the_title($ancestor) . '</a></li>';
        }
      }

      $output .= '<li>' . get_the_title() . '</li>';
    } elseif (is_author()) {
      $output .= '<li>Author Archives</li>';
    } elseif (is_search()) {
      $output .= '<li>Search Results</li>';
    } elseif (is_404()) {
      $output .= '<li>Page Not Found</li>';
    }
  }

  $output .= '</ul>';

  return $output;
} 
  1. 在需要显示面包屑导航的地方,使用以下代码调用:
<?php echo get_breadcrumbs(); ?> 
  1. 根据需要,可以自定义面包屑导航的样式和内容。
大家谈论
    我的见解