[英]get_category_parents to array wordpress
Ok So I'm using wordpress and PHP. 好的,所以我正在使用wordpress和PHP。
Basicly I get a chosen category from a dropdown menu. 基本上,我从下拉菜单中选择了一个类别。 I then find it's parents.
然后我找到它的父母。
But then comes the part where I seem to fail. 但是随后出现了我似乎失败的部分。 The output of $parents is a string with the names instead of the ID's.
$ parents的输出是一个带有名称而不是ID的字符串。
So I try to get each word from the string into an array. 因此,我尝试将字符串中的每个单词放入数组中。 And loop through them and convert them to their ID number.
并循环浏览它们并将其转换为ID号。
I commented out where it doesnt seem to work. 我评论了它似乎不起作用的地方。 What am I doing wrong?
我究竟做错了什么?
//Create array
$categoriesArray = [];
//Get choice from wp-dropdown
$selected_val = $_POST['cat'];
//Get parents from choice divided by (this seems to output a string)
$parents = get_category_parents( $selected_val, true, ',' );
/*
//Make array from string
$categoriesArray = explode(",",$parents);
for ($i = 0; $i < count($categoriesArray); $i++) {
{
$categoriesArray[$i] = get_cat_ID($categoriesArray[$i]);
}
*/
//the array should look something like this.
//$categoriesArray = ["21","44"];
try this,
function get_level($cat, $level = 0)
{
if ($cat->category_parent == 0) {
return $level;
} else {
$level++;
$cat = get_category($cat->category_parent);
return get_level($cat, $level);
}
}
if (is_category()) {
$cat = get_query_var('cat');
$your_cat = get_category($cat);
echo get_level($your_cat);
}
It had to do with the name of the category. 它与类别名称有关。 I needed to use the slug instead of the name.
我需要使用子弹代替名字。
Here is my code that works. 这是我的代码。 I can now make a new post and give it a category with their parents included!
我现在可以发布一个新帖子,并给它加上父母的一个类别!
//Create array
$categoriesArray = [];
//Get choice from wp-dropdown
$selected_val = $_POST['cat'];
//Get parents from choice divided by ,
$parents = get_category_parents( $selected_val, true, ',',false);
//Make array from string
$categoriesArray = explode(",",$parents);
for ($i = 0; $i < count($categoriesArray); $i++)
{
$categoriesArray[$i] = get_cat_ID($categoriesArray[$i]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.