Passing a URL variable to category.php

I need to pass a URL variable to my category.php file.
Currently my category page is at http://example.com/category-slug/
I am using the SEO plugin to rewrite http://example.com/category/category-slug and remove the /category/ part.

Also, the settings formy permalinks are set to this option in the settings menu: http://example.com/sample-post/

Read More

Now I need to be able to pass a variable in the URL like:

http://example.com/category-slug/?type=VALUE 

or

http://example.com/category-slug/VALUE

where “type” is the name of the variable and VALUE is its value

I have tried using this piece of code in my functions.php file:

<?php    
   add_filter('query_vars', 'parameter_queryvars' );
   function parameter_queryvars( $qvars )
     {
        $qvars[] = 'type';
        return $qvars;
     }
    global $wp_query;
     if (isset($wp_query->query_vars['type']))
      {
        print $wp_query->query_vars['type'];
      }
?>

However, when I try to open http://example.com/category-slug/?type=something or http://example.com/category-slug/something I get “nothing found” and “Page not found” pages.

While I see this has been discussed over and over, none of the solutions seem to work for my case.
How do I properly pass a variable to a category page?

Related posts

Leave a Reply

1 comment

  1. First of all, you code will never reach the if statement, as you return from the function before.

    I also don’t know which SEO tool you are using, but there is one function that goes with the “query_vars” filter: add_rewrite_rule()

    I would recommend to write a little plugin which does the rewriting of the category permalink. Something like this (untested, but similar to a plugin I use):

    // Flush added rewrite rules on activation
    function category_permalink_rewrite_activate() {
        category_permalink_rewrite_set_rewrite_rules();
        flush_rewrite_rules();
    }
    register_activation_hook( __FILE__, 'category_permalink_rewrite_activate' );
    
    // Remove rewrite rule for event archives
    function category_permalink_rewrite_deactivate() {
        flush_rewrite_rules(); 
    }
    register_deactivation_hook( __FILE__, 'category_permalink_rewrite_deactivate' );
    
    // Add rewrite rule for category permalink on init
        add_rewrite_rule( '^category-(.*)/(.*)', 'index.php?category_name=$matches[1]&type=$matches[2]', 'top' );
    kaufunction category_permalink_rewrite_set_rewrite_rules() {
    }
    add_filter( 'init', 'category_permalink_rewrite_set_rewrite_rules' );
    
    // Register the custom query var so WP recognizes it
    function category_permalink_rewrite_add_query_vars( $vars ) {
        $vars[] = 'type';
        return $vars;
    }
    add_filter( 'query_vars', 'category_permalink_rewrite_add_query_vars' );