I am trying to get rid of WP folders and rewrite URL for my custom PDF created a document based on ID of the product. I used the code below but it's not working.

Initial value: http://example.com/wp-content/themes/exampletheme/templates/pdf-generator.php?productID=11

The value I am trying to get: http://example.com/carPDF=11


add_action('init', 'custom_rewrite_basic');
function custom_rewrite_basic() {
    add_rewrite_rule('carPDF=([0-9]+)/?$', 'wp-content/themes/exampletheme/templates/pdf-generator.php?productID=$matches[1]', 'top');

I was able to figure out myself, but now I get permalink like http://example.com/carPDF/?productID=61 I want to remove get parameter and instead have the only number like this http://example.com/carPDF/61

CODE UPDATED: functions.php

add_action('init', 'custom_rewrite_pdfURL');
function custom_rewrite_pdfURL() {

    add_rewrite_rule('^carPDF/([^/]*)/?', 'wp-content/themes/exampletheme/templates/pdf-generator.php?productID=$matches[1]', 'top');


<form method="GET" action="http://example.com/carPDF/" id="hidden-pdf-form">
    <input type="hidden" value="<?php echo "$id"; ?>" name="productID">
    <i class="glyphicon glyphicon-download"></i>
    <input type="submit" value="Download PDF" class="btn btn-link"/>
  • Did you update the permalinks after adding the new rewrite rule? – kero Jul 18 '17 at 14:38
  • Yep currently I was able to achieve this http://example.com/carPDF/62?productID=62 I want to get rid of ?productID=62. @kero I am using hidden form to pass get parameter with action attribute: action="http://example.com/carPDF/<?php echo "$id";?>" – Soothsayer92 Jul 18 '17 at 14:55

$matches[1] doesn't work for external redirects, only internal (URL must start with index.php and handled by WordPress itself)

Try this

add_action('init', 'custom_rewrite_pdfURL');
function custom_rewrite_pdfURL() {
    add_rewrite_rule('^carPDF/([^/]*)/?', 'wp-content/themes/exampletheme/templates/pdf-generator.php?productID=$1', 'top');

Don't forget to flush permalinks

| improve this answer | |
  • It works, thanks, I can access the URL directly but when I am trying to enter it via link (in form via get attribute) it adds ?productID=62. Any idea how to change this? – Soothsayer92 Jul 19 '17 at 7:25
  • You don't need <input name="productID">... You can have <form action="http://example.com/carPDF/<?php echo "$id"; ?>"> or just skip the form and have <a href="http://example.com/carPDF/<?php echo "$id"; ?>"> – Worduoso Jul 20 '17 at 1:59

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.