Wordpress permalinks that include name and ID but only consider ID
I have a WordPress site and I would like to emulate the way some news feeds and portals generate their URLs.
For example, you have an article titled "Man Loves a Woman" and the CMS software will generate a URL like this:
https://example.com/man-loves-woman/55123
Where 55123
is the real article ID, so
https://example.com/man-does-not-love-woman/55123
will return the same article as long as the valid id 55123
is not changed. It doesn't matter which sequence is possible, it is %postname%/%id%
or%id%/%postname%
I now have a custom permalink parameter:
/%postname%/%year%%monthnum%%day%
I'm not very happy with this, I would like to have it /%postname%/%unique_id%
where it is created by default %postname%
, but it doesn't really matter what its value is as it %unique_id%
is immutable.
I'm looking through wp-includes/link-template.php
and rewrite.php
but I'm not very good at PHP, but if someone can point me in the right direction I would appreciate it, I have some basic understanding of how this all works, with the right nudge I could follow and figure it out myself.
Maybe I'm looking at the whole thing wrong and should focus on the Nginx behind it and set up a rewrite rule we insert into %postname%
which can be anything and just use Default in the permalinks settings of WordPress which produces:
https://example.com/?p=123
source to share
You need to look at add_rewrite_rule . Add the following code to functions.php
add_action( "init", "so_27051693_permalink" );
function so_27051693_permalink() {
//This rule will match : man-loves-woman/55123
add_rewrite_rule(
'^([^/]*)/([0-9]+)/?',
'index.php?p=$matches[2]',
'top' );
//This rule will match : 55123/man-loves-woman
add_rewrite_rule(
'^([0-9]+)/([^/]*)/?',
'index.php?p=$matches[1]',
'top' );
}
In both cases, the post will be retrieved using post_id. Make sure you reset the rewrite rules by re-saving your permalinks.
source to share