问题描述
我试图设置自定义页面,而不是Wordpress的默认类别/存档页面。
我已将以下脚本复制到主题function.php中,我提到该站点使用了The7 Theme。
function loadPageFirst() {
// get the actual category
$actualCategory = get_category( get_query_var('cat') );
// get the page with the same slug
$matchingPage = get_page_by_path( $actualCategory->slug );
// If no match,load the normal listing template and exit (edit if you are using a custom listing template,eg. category.php)
if (!$matchingPage) {
include( get_template_directory() . '/archive.php');
die();
}
// Make a new query with the page's ID and load the page template
query_posts( 'page_id=' . $matchingPage->ID );
include( get_template_directory() . '/page.php');
die();
}
add_filter( 'category_template','loadPageFirst' );
我从here那里拿走了,这是本塞加兹达的解决方案。
现在,在脚本之后,如果我创建一个页面,该页面的URL与类别页面相同,则会自动替换它。
问题在于该脚本仅限于主要(父)类别。
我想创建一个自动替换相同子类别页面的子页面(例如example.com/cars/european/german)。
我的问题是如何修改脚本以包括子类别。
解决方法
您可以使用模板轻松地做到这一点。使用一个子主题,并创建一个名为category- $ slug.php的模板,并将$ slug替换为您要为其创建页面的slug。您也可以只创建一个category.php。有关更多选项,请检查此template hierarchy。
,尝试一下:
function loadPageFirst() {
// get the actual category
$actualCategory = get_category( get_query_var('cat') );
// get the page with the same slug
$matchingPage = get_page_by_path( $actualCategory->slug );
// If no match,load the normal listing template and exit (edit if you are using a custom listing template,eg. category.php)
if (!$matchingPage) {
include( get_template_directory() . '/archive.php');
die();
}
// Make a new query with the page's ID and load the page template
global $post; $post->ID = $matchingPage->ID;
query_posts( 'page_id=' . $matchingPage->ID );
include( get_template_directory() . '/page.php');
die();
}
add_filter( 'category_template','loadPageFirst' );