2

我正在尝试设置自定义页面而不是 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' );

我从这里拿了它,这是 bencergazda 的解决方案。

现在,在脚本之后,如果我创建一个与类别页面具有相同 url 的页面,它会自动替换它。

问题是脚本仅限于主(父)类别。

我想创建一个自动替换相同子类别页面的子页面(例如 example.com/cars/european/german)。

我的问题是如何修改脚本以包含子类别。

4

2 回答 2

1

试试这个:

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' );
于 2020-12-11T11:27:14.873 回答
0

您可以使用模板轻松地做到这一点。使用子主题并创建一个名为 category-$slug.php 的模板,并将 $slug 替换为您要为其创建页面的 slug。您也可以只创建一个 category.php。有关更多选项,请查看此模板层次结构

于 2020-10-18T17:19:22.290 回答