也许你还不清楚这个问题,但我会尽力解释。
有两种注册自定义帖子类型,song 和album.
我在创建Album, 在其中,我可以从Songs 列表我将向您展示放置在不同函数中的代码片段:
// SELECTED
$values = get_post_custom( $post->id );
$selected = isset( $values[\'select_song_album\'] ) ? esc_attr( $values[\'select_song_album\'][0] ) : \'\';
// SELECT - OPTION
<select name="select_song_album" id="select_song_album">
<option value="Non-album">Non-album</option>
<?php
$song_album = array( \'post_type\' => \'album\', \'orderby\' => \'title\', \'order\' => \'asc\', );
$song_album_select = new WP_Query( $song_album );
while ( $song_album_select->have_posts() ) : $song_album_select->the_post();
?> <option value="<?php the_title(); ?>" <?php selected( $selected, get_the_title() ); ?> ><?php the_title(); ?></option>
<?php
endwhile;
?>
</select>
<input type="hidden" name="meta_box_nonce" id="meta_box_nonce" value="<?php echo wp_create_nonce( \'my_meta_box_nonce\' ); ?>" />
// SAVE DATA
if( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE ) return;
if( !isset( $_POST[\'meta_box_nonce\'] ) || !wp_verify_nonce( $_POST[\'meta_box_nonce\'], \'my_meta_box_nonce\' ) ) return;
if( !current_user_can( \'edit_post\', $post_id ) ) return;
if( isset( $_POST[\'select_song_album\'] ) )
update_post_meta( $post_id, \'select_song_album\', esc_attr( $_POST[\'select_song_album\'] ) );
所以,在
Album template, 我想显示编辑/添加页面上选择的所有歌曲。我尝试了此代码,但它显示了我发布的帖子类型中的所有歌曲:
<?php
$albums = new WP_Query(
array(
\'posts_per_page\' => -1,
\'post_type\' => \'album\',
\'post_status\'=> \'publish\',
\'orderby\' => \'title\',
\'order\'=> \'ASC\'
)
);
if ( $albums->have_posts() ) :
while ( $albums->have_posts() ) :
$albums->the_post();
endwhile;
endif;
wp_reset_query();
?>
<?php
$albumID = get_post_meta( get_the_ID(), \'select_song_album\', true );
$songs = new WP_Query(
array(
\'posts_per_page\' => -1,
\'post_type\' => \'song\',
\'meta_key\' => \'select_song_album\',
\'meta_value\' => $albumID,
\'orderby\' => \'title\',
\'order\'=> \'ASC\'
)
);
?>
<?php if ( $songs->have_posts() ) : while ( $songs->have_posts() ) : $songs->the_post();
?>
<div>
<span><?php the_title(); ?></span>
</div>
<?php endwhile; endif; wp_reset_query(); ?>
你能告诉我如何显示专辑中的歌曲吗?谢谢你的回答。
UPDATE: 更改了选择选项的代码
// SELECT - OPTION
<select name="select_song_album" id="select_song_album">
<option value="0">Non-album</option>
<?php
$song_album = array( \'post_type\' => \'album\', \'orderby\' => \'title\', \'order\' => \'asc\', );
$song_album_select = new WP_Query( $song_album );
while ( $song_album_select->have_posts() ) : $song_album_select->the_post();
?> <option value="<?php the_ID(); ?>" <?php selected( $selected, get_the_ID() ); ?> ><?php the_title(); ?></option>
<?php
endwhile;
?>
</select>
<input type="hidden" name="meta_box_nonce" id="meta_box_nonce" value="<?php echo wp_create_nonce( \'my_meta_box_nonce\' ); ?>" />