Vladimir
Vladimir

Reputation: 190

Wordpress permalinks that include name and ID, but considers only ID

I have a WordPress site and I would like to mimic the way certain news outlets and portals generate their URLs.

For example, you have an article called "Man Loves Woman", and the CMS software will create an url like this:

https://example.com/man-loves-woman/55123

Where the 55123 is the real ID of the article, so

https://example.com/man-does-not-love-woman/55123

will return the same article as long as the real id, 55123, isn't altered. Doesn't matter what sequence is possible, is it %postname%/%id% or %id%/%postname%

Right now I have a custom permalink setting:

/%postname%/%year%%monthnum%%day%

I'm not particularly happy about this, I'd like to have it /%postname%/%unique_id% where %postname% is generated like that by default, but it doesn't really matter what its value is, as the %unique_id% is immutable.

I'm looking over at wp-includes/link-template.php and rewrite.php, but I'm not very versed in PHP, but if someone can point me in the right direction, I would be grateful, I have some basic understanding how it all works, with a right nudge I could follow up and figure it out on my own.

Perhaps I'm looking at it all wrong and should concentrate on Nginx behind it and setup a rewrite rule that insert the %postname% which can be anything and simply use the Default in the WordPress permalinks settings which produces:

https://example.com/?p=123

Upvotes: 3

Views: 1104

Answers (2)

Hujjat Nazari
Hujjat Nazari

Reputation: 918

If you want to display the unique id of the post after it's name, you can do that from Custom Structure inside WordPress Permalink Settings by adding this structure.

/%postname%/%post_id%

It is not working on localhost, but it is working on online website.

enter image description here

Upvotes: 3

Anand Shah
Anand Shah

Reputation: 14913

You need to look into add_rewrite_rule. Add the following code 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 the cases, the post will be fetched using post_id . Ensure to flush the rewrite rules by re-saving your permalinks.

Upvotes: 2

Related Questions