I’m new to writing rewrite rules in WordPress and I want to make sure I’m not going about this the wrong way.

My goal: to use random numbers and letters as the URL ending for my custom post type project pages

My code below is what I’ve attempted so far …

functions.php

// Create a random string and save it to the post for the URL ending
add_action('save_post','add_url_id');
function add_url_id( $id, $post ){
  $url_id = uniqid();

  if ( isset( $post->url_id ) ) {
    return;
  }
update_post_meta($id, 'url_id', $url_id );
}

// Let WordPress know about my custom query variable url_id
add_filter( 'query_vars', 'add_query_var' );
function add_query_var( $vars )
{
  $vars[] = 'url_id';
  return $vars;
}

// My rewrite rule to search for the custom post with the URL's same url_id
add_action('init', 'custom_rewrite_rule', 10, 0);    
function custom_rewrite_rule() {
  add_rewrite_rule(
    '^projects/([0-9a-z]+)/?',
    'index.php?post_type=project&url_id=$matches[1]',
    'top');
}

When I var_dump my post on the individual custom post pages, I can see that they do have a value in their url_id field. When I save this code and flush the permalinks cache, I find that I’m redirected to http://example.com/projects/, but I only see the homepage instead of the custom post. I’m guessing the issue has to do with no results being returned by my url_id variable, but I’m not sure why my query doesn’t have any result since I do have posts with this field populated.

Read more here: How to use a custom field with add_rewrite_rule()?


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: