Set up automatic creation of Post Slug in Wordpress

When we add a new message to wordpress, after submitting the message header, the pool is automatically generated. I need to edit this auto-generation module so that I can automatically add an arbitrary number to the end of the pool. How to do it?

+3
source share
5 answers

Do not use the hard-coded version that the OP uses. When he did this, there was no filter. More recently, starting with 3.3, a filter has been 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 changes the mucus every time you save a message ... Which was what I was hoping for ...

EDIT:

. , , ajax , , .

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;
}
+12

: ( functions.php)

function append_slug($data) {
global $post_ID;

if (!empty($data['post_name']) && $data['post_status'] == "publish" && $data['post_type'] == "post") {

        if( !is_numeric(substr($data['post_name'], -4)) ) {
            $random = rand(1111,9999);
            $data['post_name'] = sanitize_title($data['post_title'], $post_ID);
            $data['post_name'] .= '-' . $random;
        }

}
 return $data; } add_filter('wp_insert_post_data', 'append_slug', 10);
+2

, wp_insert_post_data, :

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);

, , WordPress , , , .

+1
   add_filter('post_link','postLinkFilter', 10, 3);

   /**
    * Manipulates the permalink
    *
    * @param string $permalink
    * @param stdClass $post
    * @return string
    */
   function postLinkFilter($permalink,stdClass $post){
        return $permalink.'?12345';
   }

, , , .

In any case, do not use rand()here or something similar, since the function should return the same link for the same record every time, otherwise you will have serious problems.

Good luck

0
source

You should work with wp_ajax_sample-permalink action and name_save_pre filter .

Other examples here: https://wordpress.stackexchange.com/a/190314/42702

0
source

Source: https://habr.com/ru/post/1781822/


All Articles