WordPressの記事一覧をWordPress外のPHPで読み込む
ワードプレスの記事一覧を自分のサイトのトップページに表示したいとき
最新記事から10件を抜き出し
// ■■■■■■ 記事取得 ■■■■■■ $sql = "SELECT * FROM wp_posts WHERE post_status = 'publish' AND post_title <> '' AND post_type='post' ORDER BY post_date DESC LIMIT 10"; $stmt = $db->query($sql); foreach ($stmt as $cont) { $post[] = array ( 'date' => substr( $cont['post_date'], 0 ,10 ), 'title' => $cont['post_title'], 'content' => $cont['post_content'], 'id' => $cont['ID'], 'date' => str_replace( "-" , "/" , $cont['post_date']) ); } $i = 0; foreach ($post as $val){ $postid = $val['id']; // ■■■■■■ 記事中からアイキャッチを取得 ■■■■■■ $eyeSql = "SELECT meta_value FROM wp_postmeta WHERE meta_key = '_thumbnail_id' AND post_id = :postid"; $eyeStmt = $db->prepare($eyeSql); $eyeStmt -> bindValue(':postid' ,$postid ,PDO::ERRMODE_EXCEPTION); $eyeStmt -> execute(); $metaid = $eyeStmt->fetch(); if (isset($metaid['meta_value'])) { $metaid = $metaid['meta_value']; $metaSql = "SELECT guid FROM wp_posts WHERE ID = :metaid"; $metaStmt = $db->prepare($metaSql); $metaStmt -> bindValue(':metaid' ,$metaid ,PDO::ERRMODE_EXCEPTION); $metaStmt -> execute(); $imgURL = $metaStmt->fetch(); $eyeChach = $imgURL['guid']; $post[$i]['eyecatch'] = $eyeChach; $i++; } else { // ■■■■■■ 画像がない場合はnoImg.png ■■■■■■ $post[$i]['eyecatch'] = "/common/images/noImg.png"; $i++; } }
<div class="contents"> <?php foreach ($post as $val) { ?> <div class="articleBoxWide"> <a href="/blog/?p=<?php echo $val['id']; ?>"> <div class="headImages"> <img src="<?php echo $val['eyecatch']; ?>"> </div> <dl class="headLineinBOX"> <dd class="comment"><?php echo $val['content']; ?></dd> <dd class="title"><?php echo $val['title']; ?></dd> <dd class="postTime"><?php echo $val['date']; ?></dd> </dl> </a> </div> <?php } ?> </div>