Is it possible to rewrite this kind of action url on all the posts of a custom post type?

Original url:


(Desired Output) Rewriting to:


123 = postid

Is it possible to do it with wordpress's functions instead of direct .htaccess edit?


3 Answers 3


I just realized i used different kind of rewriting which didn't require @Jacob's codes (using add_rewrite_endpoint)

add_action('init', 'wpse42279_add_endpoints');
function wpse42279_add_endpoints()
    add_rewrite_endpoint('play', EP_PERMALINK);

And then i used this conditionals on the single page:

global $post;
$pid = $post->ID;
$var = get_query_var( 'play' ); 
if( !empty($var) and $var == $pid) :
// do stuff

Now here's the working pretty link:


Instead of: example.com/custompostype/post-title/?play=123

However the problem now is that the old url still exist (example.com/custompostype/post-title/?play=123) and still accessible/visible. Is it possible to make it work like how this code works:


(It redirects to the pretty link: example.com/custompostype/post-title/)


I'm pretty sure if you need to use the action parameter you will have some mixed results, as this is one WordPress uses under the hood for a lot of things. If you have flexibility over the name of the parameter, this is indeed possible. I am unable to test this at the moment but this should get you headed in the right direction.

function wpse_cpt_rewrite_rule() {
add_action('init', 'wpse_cpt_rewrite_rule', 10, 0);

It should be noted that if you don't use the action parameter, you'll need to register your custom param like so as well.

function wpse_add_custom_tag() {
    add_rewrite_tag('%my_custom_action%', '([^&]+)');
add_action('init', 'wpse_add_custom_tag', 10, 0);
  • Thanks! It worked. Just a quick question tho. The original url is still accessible. (example.com/custompostype/post-title/?play=173/) Is it possible to automatically change it to the pretty link (example.com/custompostype/post-title/play/123/) just like how this work: example.com/?p=1 (it redirects to example.com/post-title) Dec 14, 2017 at 8:02

Assuming that you have the page (new URL) already functional, use this:


if(strpos($current_url, '?action=')) {
    $action = $_GET['action'];
    wp_redirect( 'example.com/custompostype/post-title/' . $action, $status = 301 );
  • That's a redirect. Asker wants to rewrite. It's the getting that URL functional that they're asking about. Dec 13, 2017 at 11:16
  • Thanks for your time. However, like what Jacob said, i was actually asking about rewriting instead of redirecting. Dec 13, 2017 at 12:57

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.