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.
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.