Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
parent component visible in child pages as well
#1
1. I want to use the parent page's sidebar component for all of its child pages. What code do I use?

2. Also if a page does not have a component is there a code I can use to direct that page to a different component-less template?
Reply
#2
Simple way just for one component for a parent and its subpages:
Code:
<?php if (get_parent(0)=='page' or get_page_slug(0)=='page') get_component('componentname'); ?>
For several pages and components you could repeat this line.

But here's another more complete and flexible solution:

Code:
<?php
$pagecomp = array(
    'page-1' => 'component-a',
    'page-2' => 'component-b',
    'page-3' => 'component-c' // no comma in last one
);
$thecomp = '';
foreach($pagecomp as $key=>$value) {
    if (get_parent(0)==$key or get_page_slug(0)==$key) {
        $thecomp = $value;
        break;
    }
}
if ($thecomp != '') {
    get_component($thecomp);
} else {
    get_component('component-x'); // for pages/parents that are not in the array
}
?>

component-x is the default component, if the current page is not page-1, page-2 or page-3 or their children.
Reply
#3
Thanks. This works great.

Can I apply the same principle for parent header image displaying in child pages as well? What code do I use?
Reply
#4
I can do another piece of code (different approach) to be used for both components and header image, if you don't mind using names like e.g. component comp-page1 and image header-page1.png for page1 and its child pages. (This would make it simpler.)
Reply
#5
Carlos Wrote:I can do another piece of code (different approach) to be used for both components and header image, if you don't mind using names like e.g. component comp-page1 and image header-page1.png for page1 and its child pages. (This would make it simpler.)

Could you do that please? Always a sucker for trying out more and simpler ways to get the desired result.
Reply
#6
(I haven't tested this, I hope it works :-))

Insert this code somewhere at the beginning of your template (or in your theme's functions.php file):

Code:
<?php
$myslugs = array('page1','page2','page3'); // <-- edit this

if (in_array(get_parent(0),$myslugs)) {
    $pageorparent = get_parent(0);
} elseif (in_array(get_page_slug(0),$myslugs) {
    $pageorparent = get_page_slug(0);
} else {
    $pageorparent = 'default';
}
?>

Now, to display the component:

Code:
<?php get_component('comp-'.$pageorparent); ?>

And to display the header image:

Code:
<img src="<?php get_site_url(); ?>data/uploads/header-<?php echo $pageorparent; ?>.png">

(change .png to your preferred image file extension)

- page1 and its child pages will display component comp-page1 and header image header-page1.png
- if a page is not in the list ($myslugs), component comp-default and image header-default.png will be displayed.
Reply




Users browsing this thread: 2 Guest(s)