Search code examples
wordpressgetuniquetitlepermalinks

How Get Unique meta title (post number), when Post Title already exist


As i know, WordPress automatically adds suffix in the end of permalink (post name) if a post with the same name already exists in the database.

But not adds suffix in the end of Meta title, because its depend on themes.

Anyway im using Thesis Themes, no duplicate meta title for archive meta title,

HOEMPAGE

mydomainname.com = in page 1, the title is <title>My Homepage Title</title>

mydomainname.com/page/2 = in page 2, the title is <title>My Homepage Title — Page 2</title>

CATEGORY

mydomainname.com/category/category-title = in page 1, the title is <title>My Category Title</title>

mydomainname.com/category/category-title/page/2 = in page 2, the title is <title>My Category Title — Page 2</title>

TAGS Its same, always unique dynamically.

More and more page 3,4,5++ title still unique (not duplicate) AUTOMATICALLY.

Im using Thesis Themes on my blog (Public user can update post on Fropnt End), user only create post on Front End, Authors can't access my wp-admin CMS and Thesis "Details and Additional Style" fields. So, How about Post Entry Title? How to get this features when user Create New Post with the same Title?

Example, im trying to do like below:

webresepi.com/sambal-udang = first post meta title is <title>Sambal Udang</title>

webresepi.com/sambal-udang-2 = this post title already exist on my database, so i want this post meta title like this <title>Sambal Udang — 2</title>

get number from that permalink when Post Title is already exist on database.


Solution

  • This uses the same idea as faa, but his solution has lots and lots of things in it that will prevent it from working. Use FTP to find your theme in the folder /wp-content/themes/ and then put this piece of code in functions.php:

    add_action( 'template_redirect', function() {
    if( is_single() ) { // Is a single post
        $slug = basename( $_SERVER['REQUEST_URI'] ); // The slug e.g. sambal-udang-2
        $slug = ucwords( str_replace( '-', ' ', $slug ) );
        add_filter( 'wp_title', function( $title ) use( $slug ) {
            return $slug;
        }); // This filter overrides wp_title which is used to print the meta title. It replaces whatever would we written normally with our edited version of the slug.
    }
    });
    

    The above piece of code assumes your server uses PHP version 5.3 or later. For support on older systems, we need to do away with anonymous functions:

    add_action( 'template_redirect', 'xyz_tmplt_redirect' );
    
    function xyz_tmplt_redirect() {
        if( is_single() ) {
            add_filter( 'wp_title', 'xyz_change_title' );
        }
    }
    
    function xyz_change_title( $title ) {
        $slug = basename( $_SERVER['REQUEST_URI'] ); // The slug e.g. sambal-udang-2
        $slug = ucwords( str_replace( '-', ' ', $slug ) );
        return $slug;
    }