2
votes

I have built a custom Wordpress theme using UnderStrap. My web site uses archive pages to display the content of all categories/subcategories. The structure is like

Parent Category > subcategory

My URL structure for archive pages is www.example.com/category/parent-category/subcategory. This is working fine but now the problem is that it is still loading the subcategory content if I use following URLs

www.example.com/category/subcategory www.example.com/category/any-string/subcategory

Is there a way I can stop it and start displaying 404 errors?

I have tried a "redirect_canonical" filter but it's not helping at all.

1

1 Answers

2
votes

You have to do a couple of things to achieve what you want.

  1. Add custom rewrite rules: First you have to add the custom rewrite rules to detect a subcategory. WordPress by default won't do that.
  function theme_custom_rewrites() {
    add_rewrite_tag("%parent_category_name%", "([a-z0-9\-_]+)");
    add_rewrite_rule('^category/([a-z0-9\-_]+)/([a-z0-9\-_]+)/?', 'index.php?parent_category_name=$matches[1]&category_name=$matches[2]', 'top');

    add_rewrite_rule('^category/([a-z0-9\-_]+)/?', 'index.php?category_name=$matches[1]', 'top');
  }

  add_action('init', 'theme_custom_rewrites'); 
  1. Add the 404 status and template load code:
function load_404_page_for_subcategory_pages() {
  global $wp_query;

  $category_slug = get_query_var('category_name');
  $parent_category_slug = get_query_var('parent_category_name');

  $parent_category = get_category_by_slug($parent_category_slug);
  $category = get_category_by_slug($category_slug);

  if( !$parent_category && $category->parent != 0) {
    $wp_query->set_404();
    status_header( 404 );
    get_template_part( 404 );
    exit();    
  }
}

add_action('wp', 'load_404_page_for_subcategory_pages');

Add both of the hooks to the functions.php file and go to the settings page on the backend and save permalinks. It should work.