I've got lots of posts with the same title (home estate's properties), and i need to make url of single property -> title + ID (id part, adde automatically) after making new post.

And is it possible to change existing one's? (i've got lots of them already created)

Please help, i'm stuck

  • please share a code you're working on – Ignat B. Dec 7 '17 at 17:57

Yes, this is actually what Wordpress does automatically for you.

Navigate to Settings>Permalinks and add your custom structure you want like:

| improve this answer | |

This code will update post url when you save it:

function wpse_288020_replace_url( $post_id ) {

    $post_type = get_post_type( $post_id );

    if( $post_type === 'your_post_type' ) {

        $title = get_the_title( $post_id );
        $title = sanitize_title( $title );

        $post = array(
            'ID' => $post_id,
            'post_name' => sprintf('%s-%s', $title, $post_id),

        remove_action( 'save_post', 'wpse_288020_replace_url' ); // Remove action to prevent loop

        wp_update_post( $post );

        add_action( 'save_post', 'wpse_288020_replace_url' );

add_action( 'save_post', 'wpse_288020_replace_url' );

And this code will make mass update of all your posts urls:

function wpse_288020_batch_replace_url() {

    // Get all posts
    $query = new WP_Query(array(
        'post_type' => 'post',
        'posts_per_page' => -1,

    $posts = $query->get_posts();

    foreach ($posts as $post) {

        // Get permalink
        $title = sanitize_title($post->post_title);

        // Prepare arguments
        $args = array(
            'ID' => $post->ID,
            'post_name' => sprintf('%s-%s', $title, $post->ID),

        // Update post
        wp_update_post( $args );

add_action('init', 'wpse_288020_batch_replace_url');

If you have many posts disable creating revision posts by adding WP_POST_REVISIONS constant to wp-config.php. It will speed up script and reduce the demand for memory usage.

define( 'WP_POST_REVISIONS', false );

| improve this answer | |

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.