我建议使用短代码,因为这样可以很容易地将歌曲列表嵌入到内容的任何地方,任何页面或帖子中。
UPDATE: 我有点神魂颠倒了,结果是这样!
function song_list_shortcode( $attrs )
{
$r = ( object )wp_parse_args( $attrs, array(
\'format\' => \'%post_title - %link\',
\'link\' => \'%song_key_name\',
\'key\' => \'song_key_name\'
) );
$query = new WP_Query( array( \'meta_query\' => array( array( \'key\' => $r->key ) ), \'nopaging\' => true, \'update_post_term_cache\' => false ) );
if ( !$query->have_posts() )
return \'\';
$meta_keys = array();
foreach ( array( \'format\', \'link\' ) as $type ) {
// find meta keys
if ( !preg_match_all( \'#%([a-z0-9_-]+)#\', $r->$type, $_keys ) )
continue;
$_keys = array_flip( $_keys[1] );
unset( $_keys[\'post_title\'], $_keys[\'link\'] ); // don\'t want these, not meta keys
$meta_keys = $meta_keys + $_keys; // add new keys on to meta key stack
}
if ( !empty( $meta_keys ) )
$meta_keys = array_keys( $meta_keys );
$output = \'<ul class="songs">\';
while ( $query->have_posts() ) {
$query->the_post();
$format = $r->format;
$link = $r->link;
if ( !empty( $meta_keys ) ) {
// grab all meta data in one swoop (should be cached from query)
$meta_data = get_post_custom( $query->post->ID );
// swap out all meta key names with their actual value!
foreach ( $meta_keys as $key ) {
// using get_post_custom(), all meta data values are arrays
if ( isset( $meta_data[ $key ][0] ) )
$value = esc_html( $meta_data[ $key ][0] );
else
$value = \'\'; // meta key not found, so replace with blank
list( $format, $link ) = str_replace( "%$key", $value, array( $format, $link ) );
}
}
// swap out %post_title with actual post title
list( $format, $link ) = str_replace( \'%post_title\', get_the_title(), array( $format, $link ) );
// swap out %link in $format with actual $link
$output .= \'<li>\' . str_replace( \'%link\', \'<a href="\' . get_permalink() . \'">\' . $link . \'</a>\', $format ) . \'</li>\';
}
wp_reset_postdata();
$output .= \'</ul>\';
return $output;
}
add_shortcode( \'song-list\', \'song_list_shortcode\' );
你可以这样使用它;
[song-list format="%post_title - %link - %song_date_meta_key"]
// The post title - <a href="/post/">Song Name</a> - Song Date
查看如何使用
%
指示一个元键,它将在运行时与值交换。
还要注意的是%post_title
和%link
是两个特殊参数,分别与文章标题和锚定链接交换。
您还可以以相同的方式格式化链接文本的内容;
[song-list link="Date: %song_date_meta_key"]
// Post Title <a href="/post/">Date: Song Date</a>
最后
key
属性控制检索哪些帖子。
[song-list key="song_name"]
// Retrieves all posts with the meta key \'song_name\'
我建议用最常用的参数替换函数开头的硬编码默认值。