[WordPress] A Method for combining both of plain and custom URLs

In WordPress, we usually set the custom URLs for the purpose of SEO.
For the old plain URLs which are previously published to other sites, we should maintain them by redirecting to the new custom URLs.

The htaccess setting can simply do the redirection to a static page, such as response 404 not found or see other new site. Sometimes, we don’t know how many old plain urls are published. It cannot fulfill our needs for mapping the old plain URLs to the corresponding new URLs. For example, we want to create the following rules of redirections:

redirect http://example.com/?p=123 to http://example.com/custom/link

redirect http://example.com/?p=456 to http://example.com/the/other_links

There may be more old URLs we don’t be aware of are published. A general soluton is to keep both of the plain and custom URLs.

In this case, we use add_filter function provided by WordPress.
Navigate your directory of currently used theme and find functions.php and put a piece of codes as follows:

function compatible_link( $postlink, $redirect) {

$id = get_query_var('p', -1);
if($id !== -1 && is_numeric($id)) {
return get_permalink($id);
return $postlink;

add_filter('post_type_link', 'compatible_link', 10, 2);

Done! Enjoy your website.


  1. Rewriting URLs in WordPress: Tips and Plugins. URL: http://www.hongkiat.com/blog/wordpress-url-rewrite/
  2. WordPress的Hook機制與原理. URL: http://www.mrmu.com.tw/2011/10/10/wordpress-hook/
  3. Custom post type with post_id in permalink structure. URL: https://wordpress.org/support/topic/custom-post-type-permalink-structure
  4. Custom Login Url with plain permalink format. URL: https://wordpress.org/support/topic/custom-login-url-with-plain-permalink-format
  5. Function Reference/get query var. URL:https://codex.wordpress.org/Function_Reference/get_query_var
  6. CREATING CUSTOM PERMALINKS IN WORDPRESS. URL:http://wp-events-plugin.com/tutorials/creating-custom-permalinks-in-wordpress/
This entry was posted in PHP, Web Design, wordpress, 程式設計, 網頁撰寫. Bookmark the permalink.

Leave a Reply

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