I have implemented rewrite rule in "twentytwentyone" theme, but you may implement it elsewhere in wordpress.
For more info, please refer to this.
https://developer.wordpress.org/reference/functions/add_rewrite_rule/
Implement in wordpress Theme
- Add the following code to the bottom of next file
~/wp-content/themes/twentytwentyone/functions.php
// wp-content/themes/twentytwentyone/functions.php
...
// rewrite-rule
add_action( 'init', function() {
add_rewrite_rule( 'coupon/([a-zA-Z0-9]+)[/]?$', 'index.php?coupon=$matches[1]', 'top' );
} );
// whitelist "coupon" param
add_filter( 'query_vars', function( $query_vars ) {
$query_vars[] = 'coupon';
return $query_vars;
} );
// set template php file
add_action( 'template_include', function( $template ) {
if ( get_query_var( 'coupon' ) == false || get_query_var( 'coupon' ) == '' ) {
return $template;
}
//You can return wherever you want to go
return get_template_directory() . '/template-coupon.php';
} );
- Create ~/wp-content/themes/twentytwentyone/template-coupon.php
// wp-content/themes/twentytwentyone/template-coupon.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo get_query_var( 'coupon' )." from POST".PHP_EOL;
var_dump($_POST);
// check coupon validation here
// $query = $wpdb->prepare("SELECT 1"); // Your query
// $result = $wpdb->get_var($query);
// var_dump($result);
} else {
echo get_query_var( 'coupon' )." from redirection GET".PHP_EOL;
// do something
}
?>
<?php //get_template_part( 'header' ); ?>
<form action="" method="POST">
<label for="first_name">First Name</label><input type="text" name="first_name" id="first_name"><br/>
<label for="last_name">Last Name</label><input type="text" name="last_name" id="last_name"><br/>
<label for="email">Email</label><input type="text" name="email" id="email"><br/>
<input type="submit">
</form>
<?php //get_template_part( 'footer' ); ?>
Implement in wordpress Plugin (Hello Dolly)
- Add the above step 1 code to the bottom of next file
~/wp-content/plugins/hello.php
change
return get_template_directory() . '/template-coupon.php';
to
return __DIR__ . '/template-coupon.php';
- Add the above step 2 code to ~/wp-content/plugins/template-coupon.php
Refresh permalinks cache
When you add/modify URL part in step1, you need to refresh permalniks cache, otherwise wordress does not apply rewrite rule.
Settings > Permalinks > Save Changes
Result
check http://your-domain/coupon/7AD8679adO/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…