Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//ここからfunctions.php | |
function return_latest_id($cat_id=null) { | |
global $wpdb; | |
if(empty($cat_id)) { | |
// カスタムポストタイプ(foo、bar、hogeと仮定)を含む最新記事idの取得。 | |
$row = $wpdb->get_row("SELECT ID FROM $wpdb->posts WHERE ( post_type = 'post' OR post_type = 'foo' OR post_type = 'bar' OR post_type = 'hoge' ) 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' OR p.post_type = 'foo' OR p.post_type = 'bar' OR p.post_type = 'hoge') AND p.post_status = 'publish' AND r.term_taxonomy_id = '$cat_id' ORDER BY p.post_date DESC"); | |
} | |
return !empty( $row ) ? $row->ID : '0'; | |
} | |
//ここまでfunctions.php | |
?> | |
//ここから任意のファイル(index.php等) | |
<?php | |
//一番最新の記事をIDで取得 | |
$latest_id = return_latest_id(); | |
//カスタム投稿タイプも含める場合。'exclude' => $latest_idで最初の記事だけ含めない様にする | |
$args = array( 'post_type' => array('post','foo','bar','hoge'), 'numberposts' => 5 , 'exclude' => $latest_id); | |
$hoge_posts = get_posts( $args ); | |
foreach( $hoge_posts as $post ) : ?> | |
<div class="fugafuga"> | |
<span><?php the_title(); ?></span> | |
</div> | |
<?php endforeach; ?> | |
//ここまで任意のファイル(index.php等) |
Note
Description | 最新1記事を除いた記事リスト。要は最新の2記事目以降のリストを表示するというものになります。需要は殆ど無さそうですが個人的に必要だったのでメモ。もっとスマートな方法ありそうです。やってることは最新の1記事のIDを取得してexcludeしてるだけ。任意のカテゴリ、任意のポストタイプにも対応出来ます。「最初の記事だけclassを与える、任意のマークアップでスタイルを変える」だけでは対応できないケースに遭遇したので本コードで暫定的に対処しました。 |
---|---|
WordPress Ver. | 4.5.3 |
Via | http://www.is-p.cc/wordpress/original-function/get-latest-id/711 |