WordPress的面包屑
我最近一直在使用Wordpress中的面包屑痕迹,所以我认为我可以将代码发布在这里,以防其他人发现它有用。基本思想是尝试找出当前页面在站点中的位置。这意味着与父母一起检查页面和类别。到达帖子级别后,我们需要尝试一些操作,以找出当前帖子在网站中的位置。
一旦尾迹数组中充满了项目,它就会循环遍历并转换为字符串。
要使用此功能,请将以下代码放入functions.php模板中的文件中。
' > ',
'linkFinal' => false,
'echo' => true,
'printOnHome' => true,
'before' => '',
'after' => '',
);
//将默认值与参数合并。
$options = array_merge($defaults, (array)$args);
//使用当前帖子初始化跟踪。
$trail = array($post);
//初始化输出。
$output = '';
$currentCategory = 0;
if (is_front_page() == true && $options['printOnHome'] == false) {
/**
* If this is the front page and the option to prevent priting on the
* home page is disabled then echo or return the empty string depending
* on the echo option.
*/
if ($options['echo'] == true) {
echo $output;
}
return $output;
}
if (is_page()) {
//如果当前页面是页面。
$parent = $post;
while ($parent->post_parent) {
$parent = get_post($parent->post_parent);
array_unshift($trail, $parent);
}
} elseif (is_category()) {
//当前页面是类别页面。
$trail = array();
$currentCategory = get_query_var('cat');
$category = get_category($currentCategory);
while ($category->category_parent > 0) {
array_unshift($trail, $category);
$category = get_category($category->category_parent);
}
//将最终类别添加到路径中。
array_unshift($trail, $category);
} else {
//当前页面将是一个帖子或一组帖子。
$path = explode('/', $_SERVER['REQUEST_URI']);
$path = array_filter($path);
while (count($path) > 0) {
$page = get_page_by_path(implode('/', $path));
if ($page != NULL) {
array_unshift($trail, $page);
}
array_pop($path);
}
if (count($trail) == 1) {
//在路径中找不到页面,请尝试使用类别。
$category = get_the_category();
$category = $category[0];
while ($category->category_parent > 0) {
array_unshift($trail, $category);
$category = get_category($category->category_parent);
}
array_unshift($trail, $category);
}
}
$show_on_front = get_option('show_on_front');
if ('posts' == $show_on_front) {
//主页是帖子列表,因此将其称为“主页”。
$output .= '- \n" . $output . "
像这样在页面上打印出痕迹:
也有几个选项可用于更改功能的工作方式。这些如下:
分隔符:分隔面包屑路径中各项的字符串,默认为>。
linkFinal:是否将最后一个链接打印为链接。默认为false。
echo:是否在函数中打印出面包屑。默认为true。
printOnHome:在主页上打印面包屑。默认为true。
您可以get_breadcrumbs()使用与普通Wordpress功能几乎相同的方式来设置功能选项。可以通过这样的参数字符串或数组来实现。
' > ',
'linkFinal' => false,
'echo' => true,
'printOnHome' => false,
)
);
?>这将打印出类似以下内容的内容:
因为Wordpress是可以以多种不同方式设置的那些应用程序之一,所以我试图解决尽可能多的情况。但是,如果您尝试使用此面包屑功能,但无法正常工作,请在此处发表评论,并告诉我。
更新:添加到面包屑输出字符串的选项之前和之后。