在主题开发中,会涉及到开发自定义文章,但在首页调用中,大多数开发人员都会使用自定义页面模板。使用新的WP_QUERY非常容易,
$args = array( 'post_type' => 'download', ); $downloads = new WP_Query( $args );
包括本网站使用的Iepress主题的首页调用。都是采用的WP_QUERY。上面的代码就是我的easy digital download的商城。但是,WordPress仍将此视为页面而不是归档,如果您具有仅加载在归档上或依赖某些正文类的特定样式或脚本,则可能会出现问题。所以我谷歌到了使用pre_get_posts函数。我发现这实际上很好用,即使是分页和无限滚动脚本。所以就讲这个教程弄过来。希望对主题修改和开发的朋友有所帮助。
/**
* Load custom post type archive on home page
*
* Reference: https://iesay.com/displaying-a-custom-post-type-archive-on-the-front-page.html
*/function iesay_downloads_front_page( $query ) {
// Only filter the main query on the front-end
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
global $wp;
$front = false;
// If the latest posts are showing on the home page
if ( ( is_home() && empty( $wp->query_string ) ) ) {
$front = true;
}
// If a static page is set as the home page
if ( ( $query->get( 'page_id' ) == get_option( 'page_on_front' ) && get_option( 'page_on_front' ) ) || empty( $wp->query_string ) ) {
$front = true;
}
if ( $front ) :
$query->set( 'post_type', 'download' );
$query->set( 'page_id', '' );
// Set properties to match an archive
$query->is_page = 0;
$query->is_singular = 0;
$query->is_post_type_archive = 1;
$query->is_archive = 1;
endif;
}
add_action( 'pre_get_posts', 'iesay_downloads_front_page' ); - 提示:这篇文章发布于 2019/05/22,作者 99839,总计 1141 字.
- 原文: 首页上显示自定义文章类型循环 | 爱壹主题
























