The question:
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?
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Method 1
There should be no problem with unset
. There is your answer. What matters with a filter is what you return and unset
ing those keys before your rebuild the string and return it, works.
You are doing too much processing by explode
ing 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