Force WordPress to generate post slug from title only on specific custom post types
P粉514458863
P粉514458863 2024-03-31 18:58:26
0
1
361

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粉514458863
P粉514458863

reply all(1)
P粉985686557

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 );
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!