WordPressで関連書籍エントリを表示しよう

タイトルとタグに同じ文字列を指定して、かつ、カテゴリがBookであるエントリに書籍一覧を記載しているとします。こういったエントリのコンテンツは、他のエントリにおいて、関連書籍として紹介するときに利用ができます。

エントリで指定したタグと同一のタグを持ち、かつ、Bookカテゴリが指定されているエントリを取得して、その中でタグとタイトルが一致しているもののコンテンツを表示するには、次のようにします。自分自身のエントリが表示されているときは、同じコンテンツ内容を関連書籍として表示する必要はないので抑制します。

<?php
$post_tags = get_the_tags($current_entry_id);
foreach ($post_tags as $post_tag) : 
  $cat_book_id = get_cat_ID("Book");
  $same_tag_posts = get_posts("category=" . $cat_book_id . "&tag=" . $post_tag->slug);
  if ($same_tag_posts) {
    foreach ($same_tag_posts as $post_t) :
      if (strcmp($post_t->post_title, $post_tag->name)==0 && $current_entry_id!=$post_t->ID) {
?>
        <div style="border:solid 1px #ccc; padding:4px; margin-top:4px;">関連書籍:
        <?php
        echo '<a href="' . get_permalink($post_t -> ID) . '">' . $post_t->post_title . '</a><br />';
        echo $post_t->post_content;
        ?>
        </div>
<?php
      }
    endforeach;
  }
endforeach;
?>
同じタグの記事: PHP
同じタグの記事: WordPress
同じカテゴリの記事: General
関連書籍: PHP
関連書籍: WordPress