固定ページにショートコードで特定カテゴリ記事一覧(抜粋含む)表示
-
固定ページにショートコードを使って、特定のカテゴリの記事一覧をサムネイルと抜粋を含めて表示したいと思い、色んなサイトから切り貼りしてfunction.phpに下記のコードを書いたのですがうまく行きません。
// ショートコード add_shortcode('list_posts', 'my_list_posts'); function my_list_posts($atts) { // デフォルトテンプレート $template = '<h3 class="entry-title"><a href="%s" rel="bookmark">%s</a></h3> <div class="entry-summary clear"> <a href="%s" rel="bookmark">%s</a>%s<a href="%s" rel="bookmark">→ 続きを読む</a> </div><!-- .entry-summary --> '; // 引数の処理 extract(shortcode_atts(array( 'template' => $template, 'args' => 'post_type=post&posts_per_page=10', ), $atts)); $the_list = ''; // 最新のポスト取得 $postslist = get_posts($args); //$postslistにget_postsで取得したデータを入れる foreach ($postslist as $post) { //ひとつずつ取り出して繰り返し出力する $the_list .= sprintf( $template, esc_attr(get_permalink($post->ID)), esc_html($post->post_title), esc_attr(get_permalink($post->ID)), get_the_post_thumbnail($post->ID,array(160,160)), str_replace( "\n", "",get_the_excerpt()), esc_attr(get_permalink($post->ID)) ); } return $the_list; }
上記だと、固定ページの抜粋が並ぶだけでうまくいかず、get_the_excerpt()は、記事idではとってこれないみたいなので、下記のサイトを参考に関数を使いました。
http://little.ws/201302/556.html`
// ショートコード
add_shortcode(‘list_posts’, ‘my_list_posts’);
function my_list_posts($atts) {
// デフォルトテンプレート
$template = ‘<h3 class=”entry-title”>%s</h3>
<div class=”entry-summary clear”>
%s%s→ 続きを読む
</div><!– .entry-summary –>
‘;
// 引数の処理
extract(shortcode_atts(array(
‘template’ => $template,
‘args’ => ‘post_type=post&posts_per_page=10’,
), $atts));$the_list = ”;
// 最新のポスト取得
$postslist = get_posts($args);
//$postslistにget_postsで取得したデータを入れる
foreach ($postslist as $post) {
//ひとつずつ取り出して繰り返し出力する
$the_list .= sprintf(
$template,
esc_attr(get_permalink($post->ID)),
esc_html($post->post_title),
esc_attr(get_permalink($post->ID)),
get_the_post_thumbnail($post->ID,array(160,160)),
str_replace( “\n”, “”,ltl_get_the_excerpt($post->ID)),
esc_attr(get_permalink($post->ID))
);
}
return $the_list;
}
// 記事IDで抜粋を取得する
function ltl_get_the_excerpt($post_id){
global $post;
$post_bu = $post;
$post = get_post($post_id);
$output = get_the_excerpt();
$post = $post_bu;
return $output;
}
‘
うまくとれるかと思ったのですが、抜粋だけが、はじめに固定ページの抜粋が表示、次から記事の抜粋が表示と一つずれて表示されてしまいました。
これを治すにはどうすればよいでしょうか?
- トピック「固定ページにショートコードで特定カテゴリ記事一覧(抜粋含む)表示」には新たに返信することはできません。