You can use the Redirection plugin for WordPress to automatically redirect the shorter URL to the longer URL.
To use the Redirection plugin:
Install and activate the Redirection plugin.
Go to Tools > Redirection in your WordPress dashboard.
Click on the Add New button.
In the Source URL field, enter the shorter URL (/my-subpage).
In the Target URL field, enter the longer URL (/parent-page/my-subpage).
Leave the other settings as they are and click on the Add Redirect button to save the redirect.
The plugin will now automatically redirect any traffic going to the shorter URL to the longer URL.
Alternatively, you can use the WordPress Rewrite API to create custom rewrite rules for your URLs. This will allow you to define the redirect rules directly in your theme’s functions.php file.
To use the Rewrite API:
Open your theme’s functions.php file.
Add the following code to the file:
Copy code
function custom_rewrite_basic() {
add_rewrite_rule(‘^my-subpage/?’, ‘index.php?pagename=parent-page/my-subpage’, ‘top’);
}
add_action(‘init’, ‘custom_rewrite_basic’);
This code will create a custom rewrite rule that will redirect any traffic going to /my-subpage to /parent-page/my-subpage.
You can add as many rewrite rules as you need by adding more lines of code similar to the one above.
Note that you may need to flush the rewrite rules after adding them by going to Settings > Permalinks in your WordPress dashboard and clicking on the Save Changes button.
I hope this helps! Let me know if you have any questions.