phpwordpresscategoriescustom-pages

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.


Solution

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