Wordpress, get ID's of multiple categories from the URL

隐身守侯 提交于 2020-01-24 00:57:27

问题


I'm using WordPress 2.8.4.

My question is, if I'm viewing a sub category (cat-slug-2 in this example) is there a built in function to get it's category ID and its parents category ID?

Here's an example URL, where cat-slug-2 is a sub category of cat-slug-1

http://www.foo.com/category/cat-slug-1/cat-slug-2/


回答1:


Maybe something like this?

<?php
    $current_category = single_cat_title("", false);
    $category_ID = $wpdb->get_var( "SELECT term_id FROM $wpdb->terms WHERE slug = '" . $current_category . "'" );
    echo(get_category_parents($category_ID, TRUE, ' &raquo; '));
?>

For more info on the WP Functions/Template Tags used above, see single_cat_title and get_category_parents.




回答2:


Thanks for the answer Manzabar, from your code i was able to modify it to get what i wanted.

Ultimately, I wanted an array of the category's parentIDs. Here's how I did it:

$parents = get_category_parents($cat, false, '^%%^');
$parents = explode('^%%^', $parents);
$parentIDs = array();
foreach($parents as $parent){
    if (is_null($parent) || empty($parent)){
        continue;
    }
    $parentIDs[] = get_cat_ID($parent);
}
echo '<pre>';
print_r($parentIDs);
echo '</pre>';

Note that $cat holds the current categoryID



来源:https://stackoverflow.com/questions/1577636/wordpress-get-ids-of-multiple-categories-from-the-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!