問題描述
我想使用 WordPress 構建電視劇資料庫。我已經遵循了一些教程,我有兩個自定義帖子型別:一個用於 movies,一個用於和 series 。我跟著 this post for the structure 。
我的問題是如何使電影和系列帖子型別之間的關係?
最佳解決方案
使用外掛
一些很好的關係外掛:
使用 Metabox
您可以使用 metaboxes 構建一個簡單的關係:
add_action( 'admin_init', 'add_meta_boxes' );
function add_meta_boxes() {
add_meta_box( 'some_metabox', 'Movies Relationship', 'movies_field', 'series' );
}
function movies_field() {
global $post;
$selected_movies = get_post_meta( $post->ID, '_movies', true );
$all_movies = get_posts( array(
'post_type' => 'movies',
'numberposts' => -1,
'orderby' => 'post_title',
'order' => 'ASC'
) );
?>
<input type="hidden" name="movies_nonce" value="<?php echo wp_create_nonce( basename( __FILE__ ) ); ?>" />
<table class="form-table">
<tr valign="top"><th scope="row">
<label for="movies">Movies</label></th>
<td><select multiple name="movies">
<?php foreach ( $all_movies as $movie ) : ?>
<option value="<?php echo $movie->ID; ?>"<?php echo (in_array( $movie->ID, $selected_movies )) ? ' selected="selected"' : ''; ?>><?php echo $movie->post_title; ?></option>
<?php endforeach; ?>
</select></td></tr>
</table>
}
add_action( 'save_post', 'save_movie_field' );
function save_movie_field( $post_id ) {
// only run this for series
if ( 'series' != get_post_type( $post_id ) )
return $post_id;
// verify nonce
if ( empty( $_POST['movies_nonce'] ) || !wp_verify_nonce( $_POST['movies_nonce'], basename( __FILE__ ) ) )
return $post_id;
// check autosave
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
// check permissions
if ( !current_user_can( 'edit_post', $post_id ) )
return $post_id;
// save
update_post_meta( $post_id, '_movies', array_map( 'intval', $_POST['movies'] ) );
}
然後,把電影的關係列為系列帖子的列表:
$series = new WP_Query( array(
'post_type' => 'movies',
'post__in' => get_post_meta( $series_id, '_movies', true ),
'nopaging' => true
) );
if ( $series-> have_posts() ) { while ( $series->have_posts() ) {
$series->the_post();
?>
<li><a href="<?php%20the_permalink();%20?>"><?php the_title(); ></a></li>
<?php
} }
次佳解決方案
我推薦我剛開始使用的 Posts 2 Posts 外掛。
它允許您在帖子和頁面型別之間建立 many-to-many 關係,這意味著您可以將 movies 連結到 series 以及您可以建立的任何其他 CPT 。
此外掛還允許您建立 connection metadata,這將允許您在建立連線時獲得更精細的細節。它的使用非常靈活,允許控制管理後設資料,連線型別以及在前端顯示連線的方法。最後是 well-documented 。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。