term_taxonomy_id; }, $_terms); $result = implode(',', $_terms); return $result ?: -1; } static function get_posts($post_id = null, $num = 6, $post_types = ['post']){ global $wpdb; $post_types = implode("','", $post_types); if(is_null($post_id)){ $post_id = get_the_ID(); } $tags_multiplier = get_option('related_posts__tags_weight', 2); $categories_multiplier = get_option('related_posts__categories_weight', 1.5); $categories = self::get_post_taxonomy_terms($post_id, 'category'); $tags = self::get_post_taxonomy_terms($post_id, 'post_tag'); $tags_sql = "((SELECT COUNT(t1.term_taxonomy_id) * $tags_multiplier FROM $wpdb->term_relationships t1 WHERE t1.object_id = p.ID AND t1.term_taxonomy_id IN ($tags)))"; $cats_sql = "((SELECT COUNT(t2.term_taxonomy_id) * $categories_multiplier FROM $wpdb->term_relationships t2 WHERE t2.object_id = p.ID AND t2.term_taxonomy_id IN ($categories)))"; $date_sql = " (3/ABS(datediff( (SELECT post_date FROM $wpdb->posts WHERE ID = $post_id), p.post_date )))"; $sql = " SELECT p.ID, ( $tags_sql + $cats_sql + $date_sql ) AS num FROM $wpdb->posts p WHERE p.post_type IN ('$post_types') AND p.post_status = 'publish' AND p.ID <> $post_id GROUP BY p.ID ORDER BY num DESC, ID ASC LIMIT $num"; $result = $wpdb->get_results($sql); // echo '
'; // echo $sql; // print_r($result); // echo ''; $ids = array_map(function($el) { return $el->ID; }, $result); if(!$ids) { $ids = [-1]; } $query = new \WP_Query([ 'post__in' => $ids, 'post_type' => ['post'], 'posts_per_page' => -1, 'orderby' => 'post__in' ]); return $query; } } related_posts::init();