如果我理解得很清楚,您希望使用动态url显示您拥有的3种帖子类型中的最后一篇帖子(一篇帖子),如http://example.com/latest
.
首先,让我们将过滤器添加到\'do_parse_request\'
过滤器:
add_filter( \'do_parse_request\', function( $bool, WP $wp ) {
$home_path = trim( parse_url( home_url(), PHP_URL_PATH ), \'/\' );
$path = substr( trim( add_query_arg( array() ), \'/\' ), strlen( $home_path ) );
if ( $path === \'latest\' ) { // change \'latest\' to anything else to change the url
$wp->query_vars = array(
\'posts_per_page\' => 1, // if you want more than one post change this
\'post_type\' => array(
\'post\',
\'another_cpy\', // this should be your CPT name
\'yet_another_cpt\' // this should be your CPT name
)
);
$wp->is_latests = true;
return false; // stop WordPress parsing request
}
$wp->is_latests = false;
return $bool;
}, 0, 2);
访问以下页面时使用以前的代码
http://example.com/latest
WordPress将从3个CPT中选择最后一篇文章,但是您无法控制模板(
index.php
将使用)。
然而,一个简单的过滤器\'template_include\'
允许选择模板:
add_filter( \'template_include\', function( $template ) {
global $wp;
if ( $wp->is_latests ) {
// change the name of the templates you want to use.
// If none of the files is found in your theme folder, than index.php will be used
$locate_template = locate_template( array( \'latest.php\', \'single.php\' ) );
if ( ! empty( $locate_template ) ) {
$template = $locate_template;
}
}
return $template;
} );
仅此而已。请注意:
要查看页面,只需要一个db查询,您不需要创建页面,也不需要为范围创建页面模板,不涉及重写规则。如果您想要多篇文章,比如说3篇,并且您想要每个CPT的最后一篇文章(如@DrewAPicture 是的)您无需运行3个单独的查询即可完成。
首先是变化\'posts_per_page\' => 1
到\'posts_per_page\' => 3
在上面的代码中,在这之后将过滤器添加到\'posts_groupby_request\'
:
add_filter( \'posts_groupby_request\', function( $groupby, $query ) {
global $wp;
if ( ! is_admin() && $query->is_main_query() && $wp->is_latests ) {
$groupby = "{$GLOBALS[\'wpdb\']->posts}.post_type";
}
return $groupby;
}, PHP_INT_MAX, 2);