gpt4 book ai didi

php - 获取所有类别和帖子模板上的 WordPress 当前类别 ID 和顶级父类别 ID

转载 作者:行者123 更新时间:2023-12-02 11:04:08 24 4
gpt4 key购买 nike

假设您的 WordPress 网站具有以下结构:

Dog (Top Level Category)
-Boxer (Sub Level Category)
--Brindle (Third Level Category)
--Reverse Brindle (Third Level Category)
-Golden Retriever (Sub Level Category)
-Labrador (Sub Level Category)

Cat (Top Level Category)
-Siamese (Sub Level Category)
--Siamese Black (Third Level Category)
--Siamese White (Third Level Category)
-Bengal (Sub Level Category)
-Ragdoll (Sub Level Category)

尝试开发一个功能来添加到所有页面模板(例如category.php、single.php等),以便侧面菜单将根据您的位置显示完整的类别层次结构。例如,如果您正在查看狗类别、拳师犬或斑纹犬,它将显示与上面相同的完整狗菜单,每个菜单都链接到各自的类别,并且您所在的类别将有一个事件类别。

还在页面顶部输出顶级类别和您所在的类别。例如,如果在 Reverse Brindle 上会说“Dog > Reverse Brindle”,或者如果在 Dog 上只会说“Dog”,或者如果在 Boxer 上会说“Dog > Boxer”。

它可以正常工作,但有很多冗余代码,并且在同一页面上无法按预期工作。

最佳答案

这里有一种方法,您可以使用 wp_list_categories() 显示所有类别的完整结构化列表。 .

<?php
//Get whatever object we're working with (category or post?)
$thisObj = get_queried_object();

//If it's a post, get the category ID
if(!is_null($thisObj->ID)){
$currentCat = get_the_category();
$currentCatID = $currentCat[0]->cat_ID;
}

//If it's a category, get the ID a different way
elseif(!is_null($thisObj->term_id)){
$currentCatID = $thisObj->term_id;
}

//Call wp_list_categories to echo the list of categories
$args = array(
'current_category' => $currentCatID, //This assigns the "current-cat" class to the correct item in the list so you can style it differently
'child_of' => 0,
'hide_empty' => 0,
'order' => 'ASC',
'orderby' => 'name',
);
wp_list_categories($args);

然后您可以使用以下内容设置列表中事件类别的样式:

(您还可以使用更多的类来设置列表其余部分的样式。只需查看它生成的 HTML)

.current-cat{
/* whatever you want */
}

这应该在页面顶部完成:

<?php
$thisObj = get_queried_object(); // Find out what we're displaying (Category or post?)

if(!is_null($thisObj->ID)){ // If it's a post, get the category ID
$currentCat = get_the_category();
$currentCatID = $currentCat[0]->cat_ID;
}
elseif(!is_null($thisObj->term_id)){ // If it's a category, get the ID a different way
$currentCatID = $thisObj->term_id;
}

// Get the name of the Category we're starting with
$currentCatName = get_cat_name($currentCatID);

//Get the ID then the name of the highest parent Category
$topParentID = end(get_ancestors($currentCatID, 'category'));
$topParentName = get_cat_name($topParentID);


if(!$topParentName){ // If we're already at the highest category, just save the name
$finalAnswer = $currentCatName;
}
else{ // Otherwise, display "Top Parent > Current Cat"
$finalAnswer = $topParentName . ' > ' . $currentCatName;
}
echo $finalAnswer; //Ta-da!

关于php - 获取所有类别和帖子模板上的 WordPress 当前类别 ID 和顶级父类别 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49265865/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com