プラグインのダウンロード
プラグイン本体を下記URLからダウンロードして、有効にします。
WordPress › Relations Post Types
現時点で最新のバージョンである1.2.1を使用します。
Wordpressのバージョンは3.2.1です。
店舗と商品の関係とか
たとえば店舗と商品をカスタム投稿タイプを設定してこれらを関連付けしてみたいと思います。
そういう場合は店舗をカスタム分類を使用した方がスマートな気がしますが、カスタム分類は基本カテゴリーなのでもし店舗のページもしっかりと作り込みたいといった場合はカスタム投稿タイプにした方がいいのではないのかと思います。
カスタム投稿タイプの設定
さくっとカスタム投稿タイプの設定をしましょう。
functions.phpに以下のコードを追加します。
functions.php
/* 店舗のカスタム投稿タイプ
============================================== */
function shop_custom_post_type() {
$labels = array(
'name' => '店舗',
'singular_name' => '店舗',
'add_new_item' => '新しい店舗を追加',
'add_new' => '新規追加',
'new_item' => '新しい店舗',
'view_item' => '店舗を編集',
'not_found' => '店舗はありません',
'not_found_in_trash' => 'ゴミ箱に店舗はありません。',
'search_items' => '店舗を検索',
);
$args = array(
'labels' => $labels,
'public' => true,
'show_ui' => true,
'query_var' => true,
'hierarchical' => false,
'menu_position' => 5,
'supports' => array('title','editor')
);
register_post_type('shop', $args);
}
add_action('init', 'shop_custom_post_type');
/* 商品のカスタム投稿タイプ
============================================== */
function item_custom_post_type() {
$labels = array(
'name' => '商品',
'singular_name' => '商品',
'add_new_item' => '新しい商品を追加',
'add_new' => '新規追加',
'new_item' => '新しい商品',
'view_item' => '商品を編集',
'not_found' => '商品はありません',
'not_found_in_trash' => 'ゴミ箱に商品はありません。',
'search_items' => '商品を検索',
);
$args = array(
'labels' => $labels,
'public' => true,
'show_ui' => true,
'query_var' => true,
'hierarchical' => false,
'menu_position' => 5,
'supports' => array('title','editor')
);
register_post_type('item', $args);
}
add_action('init', 'item_custom_post_type');
Relations Post Typesの設定
プラグインを有効化してれば設定することができます。
「設定」から「Relations」を選択すると次の画面が表示されます。

作成した「店舗」と「商品」の欄もできてますね。
ここでは商品から店舗を選択したいので、商品の項目の店舗にチェックをして「Save Relations」ボタンをチェックします。
投稿する
準備ができたので投稿してみましょう。
「店舗」に適当に投稿すると、「商品」投稿画面で「店舗」という入力欄が表示されます。

カテゴリーの要領で関連付けしたい項目を選択して投稿しましょう。
ちなみに関連付けされたデータは「wp_posts_relations」という専用のテーブルに保存されます。

テンプレートの作成
関連付けされた投稿は次のようにして取得します。
rpt_get_object_relation(ポストID, 投稿タイプ名);
戻ってくる値は関連付けされたポストIDなので、「post__in」などで指定します。
今回は店舗ページで関連付けされた商品を表示したいので、「single-shop.php」に下記を記述します。
single-shop.php
<?php
$artists_relation = rpt_get_object_relation(get_the_ID(), 'item');
if ( count($artists_relation) >= 1 ) {
$args = array(
'post_type' => 'item',
'post_status' => 'publish',
'posts_per_page' => -1,
'showposts' => -1,
'post__in' => $artists_relation,
'orderby' => 'date',
'order' => 'DESC',
);
$results_artists = query_posts($args);
echo '<ul>';
foreach ( $results_artists as $post ) {
echo '<li><a href="'.get_permalink($post).'">'.get_the_title().'</a></li>';
}
echo '</ul>';
}
?>
これで店舗の詳細ページに関連付けされた商品だけ表示することができます。
