要按模板对所有帖子进行排序,您需要两个函数:一个用于查询,另一个用于添加自定义顺序。
获取帖子
function get_posts_by_template()
{
add_filter( \'posts_orderby\', \'orderby_template\' );
$query = new WP_Query(
array(
//\'meta_key\' => \'_wp_page_template\',
\'post_type\' => \'any\',
\'orderby\' => \'title\',
\'order\' => \'ASC\',
\'posts_per_page\' => -1, // dangerous
\'meta_query\' => array(
array(
\'key\' => \'_wp_page_template\',
\'value\' => \'\',
\'compare\' => \'!=\'
)
)
)
);
if ( empty ( $query->posts ) )
return FALSE;
return $query->posts;
}
更改顺序
function orderby_template( $orderby )
{
global $wpdb;
remove_filter( current_filter(), __FUNCTION__ );
$orderby = $wpdb->postmeta . \'.meta_value DESC, \' . $orderby;
return $orderby;
}
要获得良好的概述,我们可以使用以下内容:
function list_posts_by_template()
{
$posts = get_posts_by_template();
if ( ! $posts )
return print \'no posts with a template found\';
static $template = \'\';
foreach ( $posts as $post )
{
$post_template = get_post_meta( $post->ID, \'_wp_page_template\', TRUE ) . \'<br>\';
if ( $post_template !== $template )
{
print "<h2>$post_template</h2>";
$template = $post_template;
}
printf(
\'<p><a href="%1$s">%2$s</a></p>\',
get_permalink( $post->ID ),
esc_html( $post->post_title )
);
}
}