简体   繁体   中英

Set custom pages instead of category/archive pages

I'm trying to set custom pages instead of the default category/archive pages of Wordpress.

I've copied the following script into the theme function.php, I mention that the site uses 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' );

I took it from here , it's bencergazda's solution.

Now, after the script, if I create a page, which has the same url as a category page it automatically replaces it.

The problem is that the script is limited to the main (parent) category.

I want to create a child page (let's say example.com/cars/european/german) that automatically replaces the same child category page.

My question is how to modify the script to include category children.

Run a try with this:

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' );

You can easily do this by using templates. Use a child theme and make a template called category-$slug.php and replace $slug for the slug you want to make a page for. You can also just make a category.php. For more options check this template hierarchy .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM