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).

Read More

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

I need that “category-name” ID.

Related posts

Leave a Reply

6 comments

  1. 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
  2. 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;
    }
    
  3. 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?

  4. 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
    }