0

i am looking for a way to remove repeated words in wordpress slug.

let say my domain is 'example.com'

and i have a category named 'WordPress How To'

i have configured the permalinks to be 'example.com/wordpress-how-to/'

then i want to create a post with the title "How To Create A Child Theme In WordPress"

then the permalinks will automatically generate this..

'example.com/wordpress-how-to/how-to-create-a-child-theme-in-wordpress/'

since the words "wordpress,how,to" are repeated, how can i automatically remove those words when i insert the title.

i want the permalinks will autogenerate this...

'example.com/wordpress-how-to/create-a-child-theme-in/'

it's actually easy to just edit the permalinks by clicking the edit button.

but is there any functions.php code to make it autogenerated?

1 Answer 1

0

According to your example

'example.com/wordpress-how-to/how-to-create-a-child-theme-in-wordpress/'

search  = wordpress-how-to
subject = how-to-create-a-child-theme-in-wordpress/

this code removes all the words from the subject found in search term.

for more details check "Avoiding infinite loops" from save_post

 function modified_slug( $post_id ) {

     // If this is a revision, get real post ID
     if ( $parent_id = wp_is_post_revision( $post_id ) )
         $post_id = $parent_id;

      // Get default category ID from options
      $defaultcat = get_option( 'default_category' );

      // Check if this post is in default category
      if ( in_category( $defaultcat, $post_id ) ) {
         // unhook this function so it doesn't loop infinitely
         remove_action( 'save_post', 'modified_slug', 13, 2 );

         $post_url  =   get_permalink( $post_id );

         $filtered  =   array_filter( explode( '/', str_replace( home_url(), '', $post_url)));
         $search    =   explode('-', array_shift(array_values($filtered)) );
         $subject   =   end($filtered);
         $new_slug      =   trim( str_replace( $search, '', $subject ), '-' );

         // Update post
         $my_post = array(
             'ID'               =>  $post_id,
             'post_name'    =>  $new_slug
         );

         // Update the post into the database
         wp_update_post( $my_post );

         // re-hook this function
         add_action( 'save_post', 'modified_slug', 13, 2 );
     }
 }
 add_action( 'save_post', 'modified_slug', 13, 2 );
  1. https://codex.wordpress.org/Plugin_API/Action_Reference/save_post
  2. https://codex.wordpress.org/Function_Reference/wp_is_post_revision
  3. https://codex.wordpress.org/Function_Reference/wp_update_post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.