add_rewrite_rule and custom variable

I have been wanting to do something similar like this for a long time. I have a url http://studionumberone.com/portfolio/obey-clothing/ which just shows the jquery gallery of images, I then have studionumberone.com/portfolio/obey-clothing/?view=all. Which shows all of the images in the gallery one above each other.

I would like the url to be studionumberone.com/portfolio/obey-clothing/all

The custom post type just does a basic:

<?php get_header(); 
$view = $_GET['view'];
?>
<?php if ($view == "all") { ?>
show all images
<?php } else { ?>
show gallery shortcode 
<?php } ?>
<?php get_footer(); ?>

I have tried (no luck):

add_action( 'init', 'ss_permalinks' );
function ss_permalinks() {
    add_rewrite_rule(
        '([^/]+)/all/?',
        'index.php?view=all&service=$matches[1]',
        'top'
);
}
add_filter( 'query_vars', 'ss_query_vars' );
function ss_query_vars( $query_vars ) {
    $query_vars[] = 'view';
    return $query_vars;
}

1 Answer
1

Hi @westondeboer:

Since you are saying your post type is 'portfolio' here’s what works on my WordPress v3.0.4 test site with a 'portfolio' custom post type defined. It replaces all the code you have:

add_action('init','yoursite_init');
function yoursite_init() {
  global
  $wp,$wp_rewrite;
  $wp->add_query_var('view');
  $wp_rewrite->add_rule('portfolio/([^/]+)/all',
    'index.php?view=all&post_type=portfolio&name=$matches[1]', 'top');

  // Once you get working, remove this next line
  $wp_rewrite->flush_rules(false);  
}

You also need to flush your rewrite rules which you can do by saving your Permalinks in the admin console. Let me know if this solves your issue and if not please give me clarification.

UPDATE

You also need to capture the query parameter differently than using `$_GET[‘view’]’; either of these will work:

// Option 1
$view = {$GLOBALS['wp']->query_vars['view'];

// Option 2
global $wp;
$view = $wp->query_vars['view'];

Leave a Comment