global $wpdb;
$sql = 'SELECT object_id,COUNT(object_id) AS c FROM wp_term_relationships WHERE term_taxonomy_id IN (SELECT term_taxonomy_id FROM wp_term_relationships WHERE object_id = '.get_the_ID().') GROUP BY object_id ORDER BY c DESC, object_id DESC LIMIT 12;';
$object = $wpdb->get_results($sql);
$ids = [];
foreach($object as $v){
if(get_the_ID() == $v->object_id){
continue;
}
$ids[] = $v->object_id;
}
$params = [
'post_type' => 'post',
'include'=> $ids,
'orderby' => 'post__in',
];
$relposts = get_posts($params);
foreach ( array_slice($relposts,0,6) as $post ) :
setup_postdata( $post );
endforeach;
SELECT object_id,COUNT(object_id) AS c FROM wp_term_relationships WHERE term_taxonomy_id IN (SELECT term_taxonomy_id FROM wp_term_relationships WHERE object_id = '.get_the_ID().') GROUP BY object_id ORDER BY c DESC, object_id DESC LIMIT 12;
このSQLが肝
このSQLでterm一覧を取得しその中の記事を集計して関連度の高い順に取得している
includeを使うとexcludeが効かないので取得時に除外
記事数も制御できないのでarray_sliceでカット
多めに取得しているのは非公開記事や固定ページを弾くため