Rewrite rule not working, issue may be in URI request

admin2025-06-03  6

I'm trying to make a rewrite rule so that posts can be accessed both at the default and at . The code below is what I have so far. It extracts the slug from the address, uses the slug to get the post ID, and puts the slug and ID into the final rule.

function my_rewrite_rule() {
  $path = $_SERVER['REQUEST_URI'];
  $slug = basename($path);
  $url = '/' . $slug;
  $post_id = url_to_postid($url);
  add_rewrite_rule('^prefix/section2/' . $slug, 'index.php?p=' . $post_id, 'top');
}
add_action('init', 'my_rewrite_rule');

When I echo the variables, they are all correct, but when I run the rule, the second URL format gets a 404 error. The problem seems to be related to $path = $_SERVER['REQUEST_URI']. When I supply $path manually, the rule works.

I'm trying to make a rewrite rule so that posts can be accessed both at the default https://example/section1/slug and at https://example/prefix/section2/slug. The code below is what I have so far. It extracts the slug from the address, uses the slug to get the post ID, and puts the slug and ID into the final rule.

function my_rewrite_rule() {
  $path = $_SERVER['REQUEST_URI'];
  $slug = basename($path);
  $url = 'https://example/section1/' . $slug;
  $post_id = url_to_postid($url);
  add_rewrite_rule('^prefix/section2/' . $slug, 'index.php?p=' . $post_id, 'top');
}
add_action('init', 'my_rewrite_rule');

When I echo the variables, they are all correct, but when I run the rule, the second URL format gets a 404 error. The problem seems to be related to $path = $_SERVER['REQUEST_URI']. When I supply $path manually, the rule works.

Share Improve this question asked Feb 20, 2019 at 10:27 MattDMattD 31 bronze badge 1
  • The rewrite rules are meant to create a pattern that is dynamical. I is stored in the rewrite rules array and it is not efficient to add constant post id's to it. – Robbert Commented Feb 20, 2019 at 10:47
Add a comment  | 

1 Answer 1

Reset to default 0

I think you should do something like this:

function my_rewrite_rule() {
   add_rewrite_rule('^prefix/section/([0-9]+)/([^/]*)?', 'index.php?section=$matches[1]&name=$matches[2]&post_type=post', 'top');
}
add_action('init', 'my_rewrite_rule');

Add a query var for section:

function my_query_vars( $vars ) {
   $vars[] = 'section';
   return $vars;
}
add_action( 'query_vars', 'my_query_vars' );

I created the pattern for your section (which can be 1 or 2) and used $matches[2] to set the "name" parameter, which is your slug. Then I set the "post_type" to "post" to be sure WordPress is searching for a post.

Because I added the query var you can then do:

$section = get_query_var( 'section' ); 

To know which section is loaded.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748885852a314536.html

最新回复(0)