Dec 1, 2013

ほとんどのブログで目にする「この記事を読んだ方はこんな記事も読んでいます」の表示。

この「関連記事」は導入が容易なレコメンド機能として訪問者のサイト滞在時間を延ばすのに一役買ってくれます。確かに使わない手は無いですね。

今回参考にさせていただいたのはこちらのエントリ。とくに弄るところも無く、そのまんまでした。

関連記事をプラグインを使わずに表示する!WordPress高速化Tips! – ウェブソク




  • 個別記事のテンプレートファイル「single.php」の任意の場所に記述。
  • 関連付けをタグで行うかカテゴリで行うかで若干記述が変わります。

関連記事をタグで紐付ける場合

閲覧中の記事と同じタグの記事をランダムに表示します。
<?php
$tags = wp_get_post_tags($post->ID, array('orderby'=>'rand')); // 複数タグを持つ場合ランダムで取得
if ($tags) {
    $first_tag = $tags[0]->term_id;
    $args=array(
        'tag__in' => array($first_tag), // タグのIDで記事を取得
        'post__not_in' => array($post->ID), // 表示している記事を除く
        'showposts'=>3, // 取得記事数
        'caller_get_posts'=>1, // 取得した記事の何番目から表示するか
        'orderby'=> 'rand' // 記事をランダムで取得
    );
    $my_query = new WP_Query($args); 
    if( $my_query->have_posts() ) { ?>
        <ul>
        <?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <li><?php the_post_thumbnail(array(100,100)); ?>
        <p><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></p></li>
        <?php
        endwhile;
    }
    wp_reset_query();
}
?>
</ul>

関連記事をカテゴリで紐付ける場合

閲覧中の記事と同じカテゴリの記事をランダムに表示します。
<?php
$categories = wp_get_post_categories($post->ID, array('orderby'=>'rand')); // 複数カテゴリーを持つ場合ランダムで取得
if ($categories) {
    $args = array(
        'category__in' => array($categories[0]), // カテゴリーのIDで記事を取得
        'post__not_in' => array($post->ID), // 表示している記事を除く
        'showposts'=>3, // 取得記事数
        'caller_get_posts'=>1, // 取得した記事の何番目から表示するか
        'orderby'=> 'rand' // 記事をランダムで取得
    ); 
    $my_query = new WP_Query($args); 
    if( $my_query->have_posts() ) { ?>
        <ul>
        <?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <li><?php the_post_thumbnail(array(100,100)); ?>
        <p><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></p></li>
        <?php 
        endwhile;
    }
    wp_reset_query();
}
?>
</ul>

レイアウトはスタイルシートで自由に。

デフォルトでは単純な画像+記事タイトルのリスト表示になっているので、divで括るなりリストにclassを与えるなりでカスタマイズします。そんなに凝らないほうが見やすくて良いと思います。


サイト内検索
  • Author

  • Twitter

      Follow @jay0926 ( followers)
    1. Facebook