WordPress.org

Ready to get started?Download WordPress

Forums

How Do I Get The Category ID??? (6 posts)

  1. Joe Hall
    Member
    Posted 6 years ago #

    Hey Folks,

    I am in the process of writing some custom headers that will be used to refer users to our new site. I am doing this using the code below. However, I need a way to get the current category ID that is shown. I am not looking for conditional tags. Rather, I am in need of something that can pull the category ID from a global position. In other words I need something that can work in place of $get_cat as seen below:

    <?php
    switch ($$get_cat)
    {
    case 1:
      header( 'Location: http://www.newsite.com/category1' ) ;
      break;
    case 2:
      header( 'Location: http://www.newsite.com/category2' ) ;
      break;
    default:
      header( 'Location: http://www.newsite.com' ) ;
    }
    ?>
  2. Samuel Wood (Otto)
    Tech Ninja
    Posted 6 years ago #

    I'm confused. Where, exactly, are you trying to get the category ID from? What category ID are you trying to get?

  3. Joe Hall
    Member
    Posted 6 years ago #

    Thats just it Otto, I don't know where to get the category ID from. Thats what I am asking. I am trying to get any category ID that is being shown.

    The code above will be placed in the header of the site. Thus when a category page is shown the user will be redirected to the same category page on the new site.

  4. Samuel Wood (Otto)
    Tech Ninja
    Posted 6 years ago #

    So... you're trying to get the current category ID only when a category archive is being shown? If so, then this would do it:

    if (is_category()) {
    	global $wp_query;
    	$cat_obj = $wp_query->get_queried_object();
    	$cat_id = $cat_obj->term_id;
    }
  5. Joe Hall
    Member
    Posted 6 years ago #

    So, just for clarification: Using the code above, $cat_id, can then be used in my switch statement as followed?

    <?php
    if (is_category()) {
    	global $wp_query;
    	$cat_obj = $wp_query->get_queried_object();
    	$cat_id = $cat_obj->term_id;
    }
    switch ($cat_id)
    {
    case 1:
      header( 'Location: http://www.newsite.com/category1' ) ;
      break;
    case 2:
      header( 'Location: http://www.newsite.com/category2' ) ;
      break;
    default:
      header( 'Location: http://www.newsite.com' ) ;
    }
    ?>
  6. Samuel Wood (Otto)
    Tech Ninja
    Posted 6 years ago #

    Should work, yes. Although you may want to add $cat_id = 0; at the top of that code, to ensure that cat_id is set to something.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags