Home  >  Q&A  >  body text

Force WordPress to generate post slug from title only on specific custom post types

I'm using the code below to force WordPress to generate the post slug from the post title even if the user defines a different slug or copies another slug, but I want this to only affect a specific post type named job_listing but Unfortunately it affects all post types on my site.

function myplugin_update_slug( $data, $postarr ) {
if ( ! in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
    $data['post_name'] = sanitize_title( $data['post_title'] );
}

return $data;
}

add_filter( 'wp_insert_post_data', 'myplugin_update_slug', 99, 2 );

How to use the above code to target only a specific post type named job_listing without affecting other post types

Can someone help me modify this code to suit my needs?

We would be grateful for your help.

P粉514458863P粉514458863225 days ago377

reply all(1)I'll reply

  • P粉985686557

    P粉9856865572024-04-01 17:10:50

    According to the documentation $data contains post_type so you should be able to use it:

    function myplugin_update_slug( $data, $postarr ) {
        if ( $data['post_type'] === 'job_listing' && ! in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
            $data['post_name'] = sanitize_title( $data['post_title'] );
        }
    
        return $data;
    }
    
    add_filter( 'wp_insert_post_data', 'myplugin_update_slug', 99, 2 );

    reply
    0
  • Cancelreply