0

I am trying to create a custom rewrite rule for a custom post type where

This:

http://test.loc/products/directory/?c=some-value

Should become this:

http://test.loc/products/directory/some-value

Minimal code:

function create_post_type() {
  register_post_type( 'acme_product',
    array(
      'labels' => array(
        'name' => __( 'Products' ),
        'singular_name' => __( 'Product' )
      ),
      'show_ui' => false,
      'public' => true,
      'has_archive' => true,
      'rewrite' => array("slug" => "products/directory")
    )
  );
  add_rewrite_rule( 
      '^products/directory/([A-Za-z0-9-]+)/?$',
      'index.php?post_type=acme_product&c=$1',
      'top'
  );
}

I also tried like this:

add_rewrite_rule( 
    '^products/directory/?([^/]*)/?',
    'index.php?post_type=acme_product&c=$matches[1]',
    'top'
);

I simply can't get the value of 'c'. Is there something in the rewrite rule that should be different? I can't seem to get this to work.

By the way I CAN retrieve 'some-value' of 'c' from this:

 http://test.loc/index.php?post_type=acme_product&c=some-value

To retrieve the value in the template I tried both:

get_query_var( 'c' );

and

$_GET['c'];

I get nothing back...

0

SOLUTION:

I am answering my own question here since no responses were given and I presume this might be helpful to someone and in the mean while I found a solution..

I had to use the second version of 'add_rewrite_rule':

add_rewrite_rule( 
  '^products/directory/?([^/]*)/?',
  'index.php?post_type=acme_product&c=$matches[1]',
  'top'
);

I needed to register a query var,, since external query params aren't recognizable to WordPress

function 123wp_query_vars( $query_vars ){
  $query_vars[] = 'c';
  return $query_vars;
}
add_filter( 'query_vars', '123wp_query_vars' );

Then retrieve the value in the template using:

get_query_var( 'c' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.