WordPressの記事一覧を独自のSQLで取得する方法

WordPressで用意された関数で取得が難しいような特殊な記事の検索を行う場合、PHPテンプレートの直接SQLを書いて情報を取ることができます。

<?php
$results = $wpdb->get_results("SQL文");

$post_ids = null;
foreach ($results as $result) {
	$post_ids[] = $result->post_id;
}

$query = new WP_Query(array(
	'post__in' => $post_ids,
	'post_type' => 'post',
	'orderby' => 'post__in',
));

if ($query->have_posts()) {

	while ($query->have_posts()) {

		$query->the_post();

		// 記事情報出力
		the_permalink();
		the_post_thumbnail();
		the_title();
		the_date('Y.m.d');

	}
	wp_reset_postdata();

}
?>