0

I want to sanitize the title of a specific custom post type. I've managed to create a filter which sanitizes the titles. How ever It affects rest of the post types as well. After a lot of search I've managed to write an action which enables me to execute functions on specific pages on the admin panel. But I'm incapable of firing filters in actions.

So any help is appreciated.

function check_cpt( $hook_suffix ){
    $cpt = 'custom_post_type';

    if( in_array($hook_suffix, array('post-new.php', 'post.php') ) ){
        $screen = get_current_screen();

        if( is_object( $screen ) && $cpt == $screen->post_type ){

    echo'I'm only visible on custom post type';
    die;
            //add_filter( 'sanitize_title', 'url_sanitizer', 10, 3 );
            //above filter doesnt work

        }
    }
}
add_action( 'admin_enqueue_scripts', 'check_cpt');

The above action works just as I intended.How ever I cannot fire the filter. This is the filter function

function url_sanitizer( $title, $raw_title, $context) {
    $new_title = $raw_title;
    $new_title = str_replace( ' ', '_', $new_title );
    $new_title = str_replace( '-', '_', $new_title );

    return $new_title;
}
1

you want to sanitize the title or the post_name (slug)?
if you want to filter post_name you can check wp_unique_post_slug filter or you can use the wp_insert_post_data filter to filter all post data before insert or update in db.

add_filter( "wp_unique_post_slug", "url_sanitizer", 10, 4 );
function url_sanitizer( $slug, $post_ID, $post_status, $post_type ) {
    // get original title by $post_ID if needed eg. get_the_title($post_ID)
    if( $post_type == "your_cpt" ) {
        $slug= str_replace( ' ', '_', $slug);
        $slug= str_replace( '-', '_', $slug);
    }
    return $slug;
}

Reference:
wp_unique_post_slug documented in wp-includes/post.php Line No. 3790
wp_insert_post_data https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data

  • That worked exactly as I needed. I'll also check the documents. Thanks – user3067368 Jan 11 '17 at 13:42
0

if you want to filter post_name you can check wp_unique_post_slug filter or you can use the wp_insert_post_data filter to filter all post data before insert or update in db.

add_filter( "wp_unique_post_slug", "url_sanitizer", 10, 4 );
function url_sanitizer( $slug, $post_ID, $post_status, $post_type ) {
    // get original title by $post_ID if needed eg. get_the_title($post_ID)
    if( $post_type == "your_cpt" ) {
        $slug= str_replace( ' ', '_', $slug);
        $slug= str_replace( '-', '_', $slug);
    }
    return $slug;
}

Reference: wp_unique_post_slug documented in wp-includes/post.php Line No. 3790 wp_insert_post_data https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data

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.