John K
John K

Reputation: 353

wordpress: cant get category id when SEO URL is turned on

<?php
/*
Plugin Name: Members
*/

   function myFilter2($query) 
    {

        if ($query->is_category)
        {
            $currently_listing_categories = $query->query_vars['category__in'];             
            print_r($currently_listing_categories);
        }

    }

    add_filter('pre_get_posts','myFilter2');
?>

This plugin display the category ids when the url is not SEO friendly

http://domain.com/wplab/wpla4/?cat=4

. but when I turn on SEO

http://domain.com/wplab/wpla4/category/members/

the array is empty

how can I get the category id with SEO friendly urls

Upvotes: 1

Views: 745

Answers (2)

The Alpha
The Alpha

Reputation: 146191

Paste in your functions.php or use in your plugin

add_filter('pre_get_posts','myFilter2');
function myFilter2()
{
    global $wp_query;
    $cat_name= $wp_query->query_vars['name'];
    $cat_id=get_cat_id($cat_name);
    echo $cat_id; // the category id will be available, echo is for testing only
}

When url is like http://example.com/category_name

enter image description here

Upvotes: 0

Rikesh
Rikesh

Reputation: 26421

Use this function to get current cateogry in wp :

function getCurrentCatID(){

 global $wp_query;
 if(is_category() || is_single()){
  $cat_ID = get_query_var('cat');
 }
 return $cat_ID;

}

echo getCurrentCatID();

Just found for you also try this,

if(isset($wp_query->get_queried_object()->cat_ID))
{
    $cur_catId = $wp_query->get_queried_object()->cat_ID;
}
if(isset($wp_query->get_queried_object()->ID))
{
    $cur_postId = $wp_query->get_queried_object()->ID;
}

Upvotes: 1

Related Questions