How to use a custom field with add_rewrite_rule()?

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 …


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

  if ( isset( $post->url_id ) ) {
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() {

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, 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()?

Leave a Reply

Your email address will not be published. Required fields are marked *