我有一个用于在wordpress网站上创建面包屑的功能:
function the_breadcrumb() {
$delimiter = '>';
$currentBefore = '<li><a>';
$currentAfter = '</a></li>';
if ( !is_home() && !is_front_page() || is_paged() ) {
echo '<nav class="breadcrumb"><ul>';
global $post;
if ( is_page() && !$post->post_parent ) {
echo $currentBefore;
the_title();
echo $currentAfter; }
elseif ( is_page() && $post->post_parent ) {
$parent_id = $post->post_parent;
$breadcrumbs = array();
while ($parent_id) {
$page = get_page($parent_id);
$breadcrumbs[] = '<li><a href="' . get_permalink($page->ID) . '">' . get_the_title($page->ID) . '</a></li>';
$parent_id = $page->post_parent;
}
$breadcrumbs = array_reverse($breadcrumbs);
foreach ($breadcrumbs as $crumb) echo $crumb;
echo $currentBefore;
the_title();
echo $currentAfter;
}
echo '</ul></nav>';
}
}
但我希望这个函数将post_id(页面的id)作为参数,以便在为该页面创建面包屑的AJAX函数中使用它。
function ajaxify() {
$post_id = $_POST['post_id'];
$breadcrumb = the_breadcrumb($post_id);
print_r($breadcrumb);
die(); // remove trailing 0
}
我怎样才能实现这一目标?
非常感谢你的帮助。
答案 0 :(得分:0)
您需要传递post_id
作为参数,并使用wp_query检索帖子信息,如下所示:
function the_breadcrumb($post_id){
$delimiter = '>';
$currentBefore = '<li><a>';
$currentAfter = '</a></li>';
// here your query
$args = array(
'page_id' => $post_id, // id of a page, post, or custom type
'post_type' => 'any');
// here is the informations
$myPost = new WP_Query($args);
if ( !is_home() && !is_front_page() || is_paged() ) {
echo '<nav class="breadcrumb"><ul>';
if ( is_page() && !$myPost->post_parent ) {
echo $currentBefore;
the_title();
echo $currentAfter; }
elseif ( is_page() && $myPost->post_parent ) {
$parent_id = $myPost->post_parent;
$breadcrumbs = array();
while ($parent_id) {
$page = get_page($parent_id);
$breadcrumbs[] = '<li><a href="' . get_permalink($page->ID) . '">' . get_the_title($page->ID) . '</a></li>';
$parent_id = $page->post_parent;
}
$breadcrumbs = array_reverse($breadcrumbs);
foreach ($breadcrumbs as $crumb) echo $crumb;
echo $currentBefore;
the_title();
echo $currentAfter;
}
echo '</ul></nav>';
}
答案 1 :(得分:0)
此代码适用于您帖子的异步内容:(复制到functions.php中)
function ariane() {
$cat_id = get_the_category()[0]->term_id;
$breadcrumb = '<li>' . get_the_title() . '</li>';
$if_parent = TRUE;
while($if_parent == TRUE) :
$cat_object = get_category($cat_id);
$cat = $cat_object->term_id;
$categoryURL = get_category_link($cat);
$name = $cat_object->name;
$cat_id = $cat_object->parent;
$add_link = '<li><a href="' . $categoryURL . '">' . $name . '</a></li>';
$breadcrumb = substr_replace($breadcrumb, $add_link, 0, 0);
if($cat_id == 0) :
$if_parent = FALSE;
endif;
endwhile;
echo '<ul>' . $breadcrumb . '</ul>';
}
在您的archive.php或WP_QUERY循环中
<div class="ariane"><?php ariane(); ?></div>
在CSS中:
.ariane ul{
display: flex;
justify-content: flex-start;
align-items: center;
}
.ariane li:not(:last-child):after {
content: '>';
margin: 0 5px;
}