I have written a code that splits the title of the posts into words and a custom SELECT Query searches each word for the posts so that I could show better related posts under the single post.
I have included the code(related_posts.php) under my single.php. It is not echoing the post data however custom SELECT Query is working fine in phpMyAdmin but on the post page it is only printing the correct post ID whereas every other data is incorrect or empty.
The problem could be conflict in $post because I am including the code in single.php I have tried wp_reset_postdata(), wp_reset_query() but none of them worked.
<?php
/* related_posts.php */
$title = get_the_title();
//splitting words
$s_terms = explode(" ", $title);
//eliminating characters from title
$s_terms = preg_replace("/[^a-zA-Z 0-9]+/", "", $s_terms );
//sorting words by length
function term_sort($a,$b){
return strlen($b)-strlen($a);
}
usort($s_terms,'term_sort');
//formatting as "%KEY%"
$i = 0;
$st_len = count($s_terms);
foreach ($s_terms as &$s_term) {
if($i !== $st_len - 1) {
$s_term = "$wpdb->posts.post_title LIKE '%" . $s_term . "%' OR";
}else{
$s_term = "$wpdb->posts.post_title LIKE '%" . $s_term . "%'";
}
$i++;
}
unset($value);
//converting array to string with comma as a separator
$s_terms = implode(" ", $s_terms);
//query
$querystr = "SELECT SQL_CALC_FOUND_ROWS $wpdb->posts.ID FROM $wpdb->posts WHERE 1=1 AND ($s_terms) AND $wpdb->posts.post_type = 'post' AND ($wpdb->posts.post_status = 'publish' OR $wpdb->posts.post_status = 'private')";
// $querystr output : SELECT SQL_CALC_FOUND_ROWS wpku_posts.ID FROM wpku_posts WHERE 1=1 AND (wpku_posts.post_title LIKE '%Hello%' OR wpku_posts.post_title LIKE '%World%' OR wpku_posts.post_title LIKE '%Post%') AND wpku_posts.post_type = 'post' AND (wpku_posts.post_status = 'publish' OR wpku_posts.post_status = 'private')
//get result
$pageposts = $wpdb->get_results($querystr, OBJECT);
if ($pageposts):
global $post;
foreach ($pageposts as $post):
setup_postdata($post);
echo get_the_ID(); //returning correct ID
the_title(); //returning nothing
echo time_ago(); //returning 2018 years ago
the_permalink(); //returning base url http://www.example.com
endforeach;
endif;
?>