最新記事以外を取得する

電脳備忘録

function.phpで定義しておく

function return_latest_id($cat_id=null) {
global $wpdb;
if(empty($cat_id)) {
// 最新記事idの取得
$row = $wpdb->get_row("SELECT ID FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC");
} else {
// カテゴリを指定した最新記事idの取得
$cat_id = intval($cat_id);
$row = $wpdb->get_row("SELECT p.ID FROM $wpdb->posts p LEFT JOIN $wpdb->term_relationships r ON p.ID=r.object_id WHERE p.post_type = 'post' AND p.post_status = 'publish' AND r.term_taxonomy_id = '$cat_id' ORDER BY p.post_date DESC");
}
return !empty( $row ) ? $row->ID : '0';
}

return_latest_id()を呼び出して最新記事を取得し、post__not_inで除外する。

$latest_id = return_latest_id();
$args = array(
'posts_per_page' => -1,
'post__not_in'=> array($latest_id)
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();

最新記事以外の記事を取得することができました。

最新記事のidを返す関数(カテゴリ指定可能)

広告

ブログの維持費に充てるでございます・・・。