im trying to show the closest matching wordpress post depending on user input. I have tried using levenstheins distance as you can see below but it doesn’t work. If anyone also know how to show the content of the posts that is selected it would be great.
The code I have this far is below. Thanks!
$gallery_args = array(
'posts_per_page' => -1,
'orderby'=> 'date',
'order'=> 'DESC',
'post_type'=> 'gallery',
'post_status'=> 'publish',
'suppress_filters' => true
);
$posts_gallery = get_posts( $gallery_args );
foreach($posts_gallery as $rows){
$post_titles = $rows->post_title;
}
$user_input = //Users input string
$shortest = -1;
foreach ($post_titles as $post_title) {
$lev = levenshtein($user_input, $post_title);
// check for an exact match
if ($lev == 0) {
$closest = $post_title;
$shortest = 0;
break;
}
if ($lev <= $shortest || $shortest < 0) {
$closest = $post_title;
$shortest = $lev;
}
}
if ($shortest == 0) {
echo "Exact match found: $closestn" . "<br />";
} else {
echo $closest;
}
}
}
Your code works, but the
$user_input
-variable is missing. With that variable set, and a manually set$post_titles
-array it will give you the closest matching post_title.I’ve included a function (at top) to display the closest post.
My testcode: