Jump to content

How to push a page into Pages?


Adam Kiss
 Share

Recommended Posts

Hi,

let's say we have a Pages object as a result of get:

$menu_items = $pages->get('/navigation/')->children();

foreach($menu_items as $item){ ...

And now we want to 'unshift' and 'push' one items into this object:

$menu_items = $pages->get('/navigation/')->children();

$home = $pages->get('/home/');
array_unshift($menu_items, $home);

$item2 = $pages->get('/item2/');
array_push($menu_items, $item2);

foreach($menu_items as $item){ ...

This obviously won't work, since '$menu_items' is not an array (well, not so obivously... I just tried it.)

So, my question is, how can we modify pages object to include (/not include) items? (without modifying site tree)

Adam  ???

P.S.: It just hit me... can we do something like:

$pages->get('/navigation/','/page/','/item2/')
Link to comment
Share on other sites

Good question. You can use the built-in append() and/or prepend() functions, i.e.

$menu_items->prepend($home); 

I believe the unshift syntax will also work:

$menu_items->unshift($home); 

You don't have to worry about modifying the site tree because you would have to actually save a $page in order to modify the site tree. In addition, none of what you are trying to do here is modifying any pages, so even if you did save a page, it wouldn't modify anything. PageArrays are runtime dynamic arrays, and aren't saved anywhere unless they are attached to something like the result of a Page reference Fieldtype.

See /wire/core/Array.php and /wire/core/PageArray.php for all the traversal and modification methods (there are a lot). For the most part, they are patterned after jQuery traversal methods, but I included alternate names like unshift() and shift() for people that prefer PHP function names.

Just for fun, here's your example all bundled on one line. :)

foreach($pages->find("parent=/navigation/")->prepend($pages->get('/')) as $item) { ...

Or even shorter:

foreach($pages->find("parent=0|/navigation/") as $item) { ...

The selector above is saying to find all pages that have no parent (i.e. "0") or have a parent called /navigation/.

Both examples above return the same result.

$pages->get('/navigation/','/page/','/item2/')

That won't work because the function only accepts one param (a selector). But because all the pages you are selecting there have the same parent, this would work:

$pages->find("parent=/, name=navigation|page|item2"); 
  • Like 2
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...