Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize the auto generation of Post Slug in Wordpress

Tags:

php

wordpress

When we add new post in wordpress, after supplying the post title, the slug is generated automatically. I need to edit that auto generation module so that i can add some arbitrary number in the end of the slug automatically. How to do it?

like image 386
Bibhas Debnath Avatar asked Dec 23 '10 11:12

Bibhas Debnath


2 Answers

Write a plugin to hook into the wp_insert_post_data filter so you can update the slug before the post is sent for insertion into the database:

function append_slug($data) {
    global $post_ID;

    if (empty($data['post_name'])) {
        $data['post_name'] = sanitize_title($data['post_title'], $post_ID);
        $data['post_name'] .= '-' . generate_arbitrary_number_here();
    }

    return $data;
}

add_filter('wp_insert_post_data', 'append_slug', 10);

Note that this function requires that you allow WordPress to auto-generate the slug first, meaning you must not enter your own slug before generating, and it cannot update existing posts with the number.

like image 38
BoltClock Avatar answered Sep 28 '22 02:09

BoltClock


Don't use the hard-coded version that the OP used here. When he did that, there was not a filter available. More recently, since 3.3, a filter was added.

add_filter( 'wp_unique_post_slug', 'custom_unique_post_slug', 10, 4 );
function custom_unique_post_slug( $slug, $post_ID, $post_status, $post_type ) {
    if ( $custom_post_type == $post_type ) {
        $slug = md5( time() );
    }
    return $slug;
}

However this method will change the slug every time you save the post... Which was what I was hoping for...

EDIT:

This kind of works for limiting the generation to just once. The only drawback is that it creates one version when ajax runs after creating the title, then it creates another, permanent slug when the post is saved.

function custom_unique_post_slug( $slug, $post_ID, $post_status, $post_type ) {
    if ( $custom_post_type == $post_type ) {
        $post = get_post($post_ID);
        if ( empty($post->post_name) || $slug != $post->post_name ) {
            $slug = md5( time() );
        }
    }
    return $slug;
}
like image 90
Jake Avatar answered Sep 28 '22 01:09

Jake