自定义SELECT查询不返回_TITLE和_PERMALINK

时间:2016-04-30 作者:Saqib Rao

我编写了一段代码,将帖子的标题拆分为单词,并使用自定义的SELECT查询搜索每个单词中的帖子,以便在单个帖子下显示更好的相关帖子。

我已经包括了代码(related_posts.php) 在我的single.php. 它不会回显帖子数据,但在phpMyAdmin中自定义选择查询工作正常,但在帖子页面上,它只打印正确的帖子ID,而其他所有数据都不正确或为空。

问题可能是$post中存在冲突,因为我在single.php 我尝试了wp\\u reset\\u postdata()、wp\\u reset\\u query(),但都没有成功。

<?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;
?>

1 个回复
SO网友:TheDeadMedic

因为$pageposts 是post id的数组,但需要将post对象传递给setup_postdata - 而是拉动对象:

SELECT $wpdb->posts.* [rest of query]
请注意,由于您没有分页,因此不需要SQL_CALC_FOUND_ROWS