0

Say I have a page Foo and I then create another page with the same name. By default, WP will change it's slung to Foo-2.
My question then is, would it be possible to change this behaviour so the slug would be Foo-bar instead of Foo-2?

In this case, the behaviour would be really simple as I only need to have -es instead of -2 on every duplicated page's slug.

4
  • Yes, it's possible. Do you want to change it programmatically ? Can you tell us more about the schema you have in mind ? – Benoti Nov 4 '16 at 12:52
  • @Benoti updated question to explain it a bit more – sysfiend Nov 4 '16 at 12:55
  • And what about the next duplicate that occurs? – Z. Zlatev Nov 4 '16 at 15:20
  • @Zlatev if there is, I'd manually give it a different slug. – sysfiend Nov 4 '16 at 15:24
1

Test you the following filter work for you:

function wpse245094_fist_duplicate_slug( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {

    // slug had to change, we must have a duplicate
    if ( $original_slug !== $slug ) {

        // try to replace `-2` with `-es`
        $new_slug = preg_replace( '#-2$#', '-es', $slug );

        if ( $new_slug !== $slug ) {
            // if a replacement occurred ensure uniqueness again. 
            $slug = wp_unique_post_slug( $new_slug, $post_ID, $post_status, $post_type, $post_parent );
        }
    }
}

add_filter( 'wp_unique_post_slug', 'wpse245094_fist_duplicate_slug', 10, 6 );

It will only try to match -2 in the end of slug, only if it changed after WP checks.

5
  • Even though this may work, it's not what I'm trying to acomplish. Instead of a page/post being given a slug and that's going to be later replaced, I would like the behaviour to be, by default, adding -es – sysfiend Nov 4 '16 at 15:59
  • This is an attempt to do exactly that. – Z. Zlatev Nov 4 '16 at 16:02
  • Since you are using $new_slug = preg_replace( '#-2$#', '-es', $slug );, you are fixing the title afterwards it's set, or am I wrong? – sysfiend Nov 4 '16 at 16:06
  • No, not after it's set but after it has been determined which is quite different. – Z. Zlatev Nov 4 '16 at 16:18
  • Alright, got it. Anyways, I'd like to know if it's possible to do it the other way, where you don't have to replace anything, even if it's this way. Thanks for your answer though, if I cannot find how to do it they way I want, I'll test that code and select your answer as the right one. Thanks again :) – sysfiend Nov 4 '16 at 16:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.