Danielp
Danielp

Reputation: 47

WordPress get category ID from URL

I have hard time trying to find the solution, does somebody know how to get this:

I have one WordPress post in more than one category, but only one is permalink category. I need to get the ID only of that permalink category (I need this info so I can take few latest posts from permalink category via custom query).

url looks like this http://domain.com/category-name/post-title

I need that "category-name" ID.

Upvotes: 4

Views: 19825

Answers (6)

Irlando Pereira
Irlando Pereira

Reputation: 21

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

Upvotes: 2

Abdo-Host
Abdo-Host

Reputation: 4103

$category = end(get_the_category());
$current = $category->cat_ID;
echo 'id='.$current . ' - name=' . $category->cat_name;

Upvotes: 1

Rees McIvor
Rees McIvor

Reputation: 121

A Good one to use is:

<?php $page_object = get_queried_object(); ?>
<h1><?php echo $page_object->cat_name; ?></h1>

Upvotes: 9

user604234
user604234

Reputation:

My answer is:

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;
}

Upvotes: 1

Rim
Rim

Reputation: 7

Wordpress chooses the oldest category as the permalink category. There's no way to change that behavior unless you use some plugin. If you choose to use a plugin you make take the category ID from plugin settings.

You can list all categories of this post and choose most relevant category. Use the following code inside The Loop:

foreach((get_the_category()) as $category) 
{
   if ( $category->cat_ID == 1000 )
      ; // DO SOMETHING
}

Upvotes: 0

theunexpected1
theunexpected1

Reputation: 1035

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?

Upvotes: 0

Related Questions