How to remove certain words from url slug

Trying to create a SEO plugin, that will remove stop words from slugs.

This is how to explode the $slug into a list, and explode the variable containing the stop words :

add_filter ('sanitize title', 'remove_false_words');
function remove_false_words($slug) {
    if (!is_Admin()) return $slug;

    $slug = explode ('-', $slug);

    foreach ($slug as $key => $word) {
        //The $slug has been exploded and retrieves its value

        $keys_false = 'a,above,the,also';
        $keys = explode (',', $keys_false);

        foreach ($keys as $1 => $wordfalse) {
            if ($word == $wordfalse) {
                unset ($slug[$k]);
            }
        }
    }
    return implode ('-', $slug);
}

Is it correct to unset the value here? Or should I use a different way of achieving the same result?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

There should be no problem with unset. There is your answer. What matters with a filter is what you return and unseting those keys before your rebuild the string and return it, works.

You are doing too much processing by explodeing your $keys_false inside a loop, and you have a typo, and you are better off just making an array instead of creating a string that you convert to an array, and PHP has a function to do what your loop is doing. I reorganized it for you.

function remove_false_words($slug) {
  if (!is_admin()) return $slug;
  $keys_false = array('a','and','above','the','also');
  $slug = explode ('-', $slug);
  $slug = array_diff($slug,$keys_false);
  return implode ('-', $slug);
}
var_dump(remove_false_words('a-boy-and-his-dog')); // proof of concept


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x