4

我很难找到解决方案,有人知道如何得到这个:

我在不止一个类别中有一篇 WordPress 帖子,但只有一个是永久链接类别。我只需要获取该永久链接类别的 ID(我需要此信息,因此我可以通过自定义查询从永久链接类别中获取一些最新帖子)。

网址看起来像这样http://domain.com/ category-name /post-title

我需要那个“类别名称”ID。

4

6 回答 6

7

一个好用的是:

<?php $page_object = get_queried_object(); ?>
<h1><?php echo $page_object->cat_name; ?></h1>
于 2015-02-03T15:41:33.993 回答
2

我的回答是:

function get_category_by_url($url) {
    foreach( (get_the_category()) as $category) {
        if ( get_category_link($category->cat_ID) == $url )
            return $category->slug;
    }
    return false;
}
于 2013-05-14T15:55:20.057 回答
0

If the post belongs to many categories, what if you're viewing the post from a second category. In that case retrieving the category ID of the permalink category may not help, since you would need the related posts of the current category in action.

For that, you can get the ID by passing the category name as follows:

<?php get_cat_ID($cat_name)?>

Does this help?

于 2012-10-09T11:17:36.710 回答
0

Wordpress 选择最旧的类别作为永久链接类别。除非您使用某些插件,否则无法更改该行为。如果您选择使用插件,您可以从插件设置中获取类别 ID。

您可以列出此帖子的所有类别并选择最相关的类别。在循环中使用以下代码:

foreach((get_the_category()) as $category) 
{
   if ( $category->cat_ID == 1000 )
      ; // DO SOMETHING
}
于 2012-10-09T11:22:16.367 回答
0
$category = end(get_the_category());
$current = $category->cat_ID;
echo 'id='.$current . ' - name=' . $category->cat_name;
于 2015-03-24T01:25:08.353 回答
0

global $wp;
  $current_url = home_url( add_query_arg( array(), $wp->request ) ); get url

$url_array = explode('/',$current_url); 
$retVal = !empty($url_array[5]) ? $url_array[5] : $url_array[4] ;
$idObj = get_category_by_slug($retVal); 
echo $idObj->name

于 2019-01-21T14:08:12.017 回答