Skip to content

Instantly share code, notes, and snippets.

@kachi
Last active August 11, 2016 02:22
Show Gist options
  • Save kachi/97872eda293d578cfc9709c04de34e6d to your computer and use it in GitHub Desktop.
Save kachi/97872eda293d578cfc9709c04de34e6d to your computer and use it in GitHub Desktop.
<?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等)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment