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...

2 Answers 2

2

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' );
0

If you just want a redirect with regex, use Yoast SEO and select Redirects and choose option Regex.

For a url go from http://example.com/products/?c=some-value to http://example.com/products/some-value use this regex expression and paste on Yoast redirect regex page:

Type: 301 Moved Permanently
Regex Expression: products/?c=/?([^/]*)/?
URL: products/$1

I hope it helps another people who wants to redirect not just add and rewrite_rule

Best,

1
  • Welcome to WPSE. Thank you for contributing. However, (bad news), GRowing appears to be asking about working with the re-write rules directly. While sometimes, yes plugins already do what we are trying to do, this is a WordPress development QnA and, generally, plugin recommendations are off-topic. If you have not done so yet, consider checking out the tour and help center to find out how things work. Mar 27, 2021 at 2:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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