Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save brandonjp/74a148c0c2604815684e1777e8d3c135 to your computer and use it in GitHub Desktop.
Save brandonjp/74a148c0c2604815684e1777e8d3c135 to your computer and use it in GitHub Desktop.
Post Title: Remove HTML Tags from Post Title on save_post - WP / Code Snippets Pro
<? // <- remove this line if you copy/paste into Code Snippets Pro
/**
* Post Title: Remove HTML Tags from Post Title on save_post
*
* On post save, if the title contains any html tags, they will be stripped out and replaced with a space. This also resets the slug.
*/
namespace WK0aky0;
function custom_strip_all_tags_replace_with_space( $string ) {
// add a space before tags, gotta keep em separated
$string = str_replace('<', ' <', $string);
// completely remove script/style elements
$string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', ' ', $string );
// strip out the tags (this will leave a space in their place bcs we kept em separated)
$string = strip_tags( $string );
// remove multiple spaces
$string = preg_replace('/\s+/', ' ', $string);
// return the string with front and back trimmed
return trim( $string );
}
function set_custom_post_title_without_tags( $post_id, $post ){
if ( 'post' == $post->post_type ) {
$title = get_the_title($post);
$new_title = \WK0aky0\custom_strip_all_tags_replace_with_space( $title );
$slug = \sanitize_title_with_dashes( $new_title,'','save' );
$slugsan = \sanitize_title( $slug );
$args = array(
'ID' => $post_id,
'post_title' => $new_title,
'post_name' => $slugsan
);
// unhook this function so it doesn't loop infinitely
remove_action('save_post', '\WK0aky0\set_custom_post_title_without_tags',999,2);
// update the post, which calls save_post again
wp_update_post( $args );
// re-hook this function
add_action('save_post', '\WK0aky0\set_custom_post_title_without_tags',999,2);
}
}
add_action( 'save_post', '\WK0aky0\set_custom_post_title_without_tags', 999, 2 );
@brandonjp
Copy link
Author

PHP snippet for Code Snippets Pro

On post save, if the title contains any html tags, they will be stripped out and replaced with a space. This also resets the slug.

CleanShot 2023-01-18 at 15 52 57

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment