+ All Categories
Home > Documents > Basic Tutorials for ProcessWire

Basic Tutorials for ProcessWire

Date post: 28-Mar-2016
Category:
Upload: mark-luscombe
View: 276 times
Download: 20 times
Share this document with a friend
Description:
Step-by-step guides to creating a simple PW website, news/blog pages and a basic gallery
Popular Tags:
36
Transcript
Page 1: Basic Tutorials for ProcessWire
Page 2: Basic Tutorials for ProcessWire

Basic Website Tutorial

Contents [hide]

1 Int roduct ion

2 What you will Learn

3 Some Post Installat ion Jobs3.1 Admin Location3.2 Clearing out unwanted content

3.2.1 Clean out the Home Page3.3 Adding some useful modules

3.3.1 Modules to add3.4 Updating JQuery

4 Template Files4.1 The Famous ProcessWire Templating System4.2 Header and Footer

4.2.1 Here is the head code:4.2.2 Here is the footer4.2.3 Here is the CSS4.2.4 Testing the layout with the Home page

5 Creat ing a Site Set t ings System5.1 Creating the Site Settings Fields

5.1.1 Site Title5.1.2 Meta Keywords and Description5.1.3 Footer Text5.1.4 Header Banner

5.2 Creating the Site Settings Template5.3 Creating the Site Settings Page5.4 Using the Site Settings

6 Adding some Content6.1 Creating the Article Fields6.2 Creating the Article Template File

6.2.1 Adding the Fields6.3 Creating a Template6.4 Creating an Article

7 Conclusion

8 See Also

More Information

For an even quicker introduction toProcessWire, try the Small ProjectWalkthrough. That will give you a veryquick taste of how PW works.

It is also a good idea to keep an eyeon the f orums which are a greatsource of inf ormation, peppered withsome alarming bouts of silliness. If itis sometimes said that you shouldjudge a product by the type of personthat uses it, then ProcessWire comesof f pretty well.

Please also check the API which hassome solid inf ormation plus a veryusef ul cheatsheet. The f ans of PWare considering having it made into ahand knitted table cloth.

This Article requires peer review

This article is complete, but may benef it f rom checking f or accuracy andgrammar, testing any code or adding f urther inf ormation that will make it

clearer.

This tutorial will takeyou through theprocess of creating abasic website usingProcessWire. It willexplain how thetemplate f iles work,how they relate totemplates in theadministration, teachyou how to createbasic site settings likeSite T it le and MetaDescription, talkabout using images,creating pages andputting it all together.

Following this tutorial,you will also be givenf urther tutorials onspecif ic commonelements such ascreating a news page,adding a JQuerySlideshow, creating acontact f orm andcreating reusable siteblocks.

Introduction

As I am constantlyreminded, there aresome very goodreasons why

ProcessWire does not comepackaged, by def ault, with acomplete Blog system, tons ofsinging and dancing JQuery addons,a set- in-stone skinning system anda big button that says "press go tocreate your instant site!" Quitesimply, it does not need them.

ProcessWire has been designed sothat a designer with some very basiccoding skills (and is great at copyingand pasting) can put together awebsite that is tailored PRECISELYto their needs and the needs oftheir client; nothing more, nothingless, but just right.

Having said that, ProcessWire alsocomes with the ability to export asite as a prof ile and re-use it inanother installation, and a growingnumber of prof iles will appear onthe site and elsewhere overtime. Butthe central core ideal will remain -how you want your site to operate and what you have in it is up to you.

I should point out that ProcessWire is f ar more than just a good solidFramework. CMS tools are there, right up f ront and ready to use; ProcessWire

Read View source View history Go Search

Log in

Page Discussion

Navig atio n

Main pageRecent changesRandom pageArticle help

Pro cesswire

HomepageDownloadsForums

T o o lbo x

What links hereRelated changesSpecial pagesPrintable versionPermanent link

Basic Website Tutorial - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Basic_Website_Tutorial 1 / 35

Page 3: Basic Tutorials for ProcessWire

is both a CMF and a CMS - you get both worlds.

What you will Learn

Being so versatile, getting started with ProcessWire might seem a bit of apuzzle. The Planet Tutorial, which you may have already done, addresses thebasics of adding content to a "page" and displaying it on a site. This tutorialwill take you back to the beginning and show you:

How to prepare ProcessWire f or developmentHow to put together a basic HTML site structure.How to create your Template Files,How to create a site settings page f or your websiteHow to create the f orm with a Template,How to create f ields and customise them f or your needsHow to utilise Fields and Pages and how to put it all together.Finally, you will learn how to create a Template with associatedTemplate File and create a page on the website.

If working with this kind of system is new to you, then this should give you asolid grounding. If you are more experienced, I apologise in advance f or anyegg-sucking advice!

Some Post Installation Jobs

I am going to assume that you have already installed the most recent copy ofProcessWire on a local server or somewhere else; if not, run of f and do thatnow. Download a copy, unzip it into a directory on your server, create adatabase and f ollow the installation instructions .

This installation already comes with a couple of pages built in and is ready togo in a very basic sort of way, but we are going to ignore all that and do somehousekeeping instead!

Admin Location

By def ault, the ProcessWire admin is at yoursite.com/processwire.

We can change that! Login to your new site. The def ault page is the Pageslist.

Click on the Admin page and the Edit link that will appear next to it. When thepage opens, go to the Settings tab.

Change the name f ield f rom processwire to something of your choice -siteadmin, perhaps. Although hardly a great security technique, it is goodpractice. However DO REMEMBER WHAT YOU CHANGED IT TOO! Unlikeother installations you cannot look at your f ile structure to check the name ofthe admin f older.

Note: When you save the page, it will throw a 404 error. That is because it hasnow lost its place. Go to yoursite.com/siteadmin (or whatever you changedthe name to) and everything will be f ine.

Clearing out unwanted content

For this tutorial, and f or any site you design, we don't want all the bits andpieces of pages that come with the def ault installation, so lets get rid ofsome of it.

In the Pages section of the admin, click on About and then Child PageExample 1.

Click edit.

On the edit page, click on Delete

Basic Website Tutorial - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Basic_Website_Tutorial 2 / 35

Page 4: Basic Tutorials for ProcessWire

Select "Move to Trash" and then click on the Move to Trash button.

Now, repeat this with the other Child page example, the about page and theTemplates page.

Leave the rest alone!

NOTE: You could simply delete the About page and that would also delete thechildren - BE CAREFUL if you don't want that to happen!

Clean out the Home Page

For the Home page, we can start by deleting some of the content - though wewant to keep the home page itself .

Click on the home page and click edit.

Keep the T it le, Headline and Body text (we will use these later), but delete therest of the text and images. So, lose the Summary, the Sidebar and theinteresting group of images.

Click on Save to complete the process.

Now, on the top menu, click on Setup and then Templates.

Click on the home template.

Remove the Summary, Sidebar and Images f ield using the trash symbol. Thiswill not delete these f ields, just remove them f rom use on the Home template.

Click Save. You will be asked to conf irm you choice. Read the warning in italics- this is worth noting!

Adding some useful modules

ProcessWire comes with many usef ul modules but not all are installed andthere are others which are really usef ul that can be downloaded.

We will start with a wonderf ul Module Manager by the irrepressible Soma f romthe PW Forums. since that will make installing and updating other modulesmuch easier.

The Module Manager allows you to download and install modules f rom themain module repository - including third party modules. That speeds things upenormously, but it must be installed f irst!

Download it here and f ollow the installation instructions given on the page.

Once it is installed, go to Setup > Modules Manager in the admin. You are nowpresented with a huge list of modules. Lets install some.

Modules to add

There are a lot of really usef ul modules available, but there are just a couplewe should install f or now. Find them in the list in your new Module Managerand click on Download in the right column.

Thumbnails - a really usef ul module f or creating multiple thumbnails ofan image on upload f or use in a pagePage Delete - makes it a lit t le simpler to delete a page

Basic Website Tutorial - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Basic_Website_Tutorial 3 / 35

Page 5: Basic Tutorials for ProcessWire

Scripts and CSS

In the /sites/templates/ directory aretwo sub directories - scripts andstyles. You can use these f or yourJavaScripts and CSS f iles. But this isnot mandatory. Since the only f ilesthat rely on these are the templatef iles, if you wish to create directoriescalled "js" and "css" - f eel f ree!

Note: Many JQuery plugins come withtheir plugin scripting and examplesexpecting js and css (and img orimages) so you may want to go withthose rather than do a lot of re-edit ing. Or you can have all of them tocover anything, of course!

Repeater - already downloaded, so just press the install button

That will do f or now.

Updating JQuery

ProcessWire comes with TWOJQuery installations - one f or thebackend and another f or the f ront.Actually, that is not the overkill thatit may seem.

The backend JQuery is intended f orthe administration of theProcessWire version that you havedownloaded. As new versions of thecore are released, so this will getupdated to match what is happeningunder the hood.

The f rontend JQuery is there f oryou to use f or your site - nothingelse in PW relies on it - so you mightas well update it to the latest version.

Navigate your way through the f ile system to /site/templates/scripts.

Delete the JQuery that is there and go and download the most recent versionf rom the JQuery website. Put it in the scripts directory.

Template Files

Bef ore worrying about content, it is a good time to sort out some basic lookand f eel design using f iles in the Template Directory.

With Process Wire there are two parts to a template:

Templates in the administration which are used f or creating groups off ields and f or some of the page logicTemplate Files in your site f ile structure which are used f or outputtingdata and the HTML construction of your site.

Templates in the administration are of ten associated with a specif ic TemplateFile, but do not need to be, which can cause a litt le conf usion. So, I will alwayssay Template File when I am talking about the actual f iles and just Templatef or the templates in the admin.

When dealing with dif f erent types of content, these are def ined by thetemplate used in the admin, so tell your clients that when creating a page to"Choose a Template" rather than "Choose a Content Type."

The Famous ProcessWire Templating System

The most f amous f act about the ProcessWire Templating System is itscomplete absence f rom any documentation (apart f rom this paragraph). Andthis is f or good reason. ProcessWire does not have a templating system.

One of the core philosophies of ProcessWire, and something that hasattracted a lot of those who now use it f or a huge variety of both complexand simple websites, is that ProcessWire outputs the results f rom data f ieldsin a very predictable and clean f ormat (allowing f or any text f ormatting thatyou may have applied when creating the f ield). It is not wrapped in any specialDIVs and does not have any natty surprises that can only be accessed usingsome convoluted protocol and a ton of JavaScript; when you type "I have askinned Cat" into a f ield, you will get back out "I have a skinned Cat." Fulldetails of how this all works will be f ound in the Category:Fields, but as f ar asthis demo is concerned, there will be no surprises.

This means that in template f iles, once you use the very simple API calls tof etch data, you are f ree to handle it in anyway you like.

If you want to design the look of your site with Dreamweaver (otherexpensive design systems are available) and paste it into a template f ile withthe calls to the f ields in the holes, you can - it will work. Indeed, just to provethe point, the basic site layout I have used f or this tutorial, I put together withan old copy of Dreamweaver.

So, to start, we can put together a very simple and tradit ional template f ilestructure consisting of a header, a f ooter and a hole in between where wecan have some f un.

The def ault installation actually comes with exactly that, but we will start f romscratch so that there is no question about the procedure or understandinghow simple this is.

Basic Website Tutorial - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Basic_Website_Tutorial 4 / 35

Page 6: Basic Tutorials for ProcessWire

The Templates Directory

ProcessWire looks in the templatesdirectory (and not in any sub-directories) f or f iles that can be usedas template f iles associated totemplates in the admin. If a f ile hasphp as the f ile suf f ix, it is a candidate.If it has the .inc suf f ix, it will beignored. In this case, we want thesef iles to be ignored. You can createadditional directories under thetemplates directory if you like. Thereis already a scripts and stylesdirectory. You may also want aseparate directory f or include f iles,just to keep things organised. Up toyou.

Header and Footer

You can design what you like, to behonest, but it might be easier just tosteal what I have here so there areno surprises later on.

Our design will have a menubar, atop masthead banner, a body area,and a f ooter with some additionalinf ormation in it.

Navigate to /site/templates/ in yourProcessWire installation.

Create a f ile called TUT_header.incand another called TUT_f ooter.inc. Iwill use the TUT_ pref ix on all f ileswe create just so it is obvious whatf iles are being used with this andf uture tutorials. There is no otherreason!

While you are about it, create aTUT_layout.css f ile in the styles directory.

You will notice that there are a f ew f iles in the templates directory.

home.php is currently used as the Template File f or the Home page inthe pages list in the admin. We will reuse that in our design f orsimplicity.sitemap.php - although we wont use this immediately, we will keep it asa usef ul ref erence.search.php - leave this here.

So, here is a very basic and f amiliar layout.

A top menu bar, a masthead, a body area and a f ooter. The two parts thatmake this up are split at the body area between the header and the f ooter.

Here is the head code:

1. <!DOCTYPE html>2. <html lang="en">3. <head>4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />5. <meta name="description" content="DESCRIPTION GOES HERE">6. <meta name="keywords" content="KEYWORDS GO HERE">7. <title>TITLE GOES HERE</title>8. <link rel="stylesheet" type="text/css" href="<?php echo $config->urls->templates?>styles/TUT_layout.css" />9. </head>10. 11. <body>12. <div id="menubar">13. <div id="navbar"> 14. <?php15. include("./TUT_topnav.inc");16. ?> 17. </div><!-- /navbar -->18. </div><!-- /menubar -->19. 20. <header id="masthead">21. <div id="header-banner">BANNER GOES HERE</div>22. </header>23. 24. <div id="wrapper">25. <div id="content">

You will notice the include statement in the middle of the page. We need tocreate another f ile to hold the navigation (note this is an update f rom theolder tutorial).

Create a f ile called TUT_topnav.inc and place the f ollowing code in it:

(This is a menu system designed originally f or Bootstrap by Soma which Ihave adapted f or our purposes here)

1. <?php2. 3. /*4. *** NOTES from Soma ***5. 6. render markup menu7. 8. @param PageArray $pa pages of the top level items9. @param Page $root root page optional, if you use other root than home page (id:1)10. @param string $output for returned string collection11. @param integer $level internally used to count levels12. @return string menu html string13. */14. 15. function renderChildrenOf($pa, $root = null, $output = '', $level = 0) {16. if(!$root) $root = wire("pages")->get(1);17. $output = '';18. $level++;19. foreach($pa as $child) {20.

Basic Website Tutorial - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Basic_Website_Tutorial 5 / 35

Page 7: Basic Tutorials for ProcessWire

21. $class = '';22. 23. // make the current page and only its first level parent have an active class24. if($child === wire("page")){25. $class .= ' active';26. } else if($level == 1 && $child !== $root){27. if($child === wire("page")->rootParent || wire("page")->parents->has($child)){28. $class .= ' active';29. }30. }31. 32. $class = strlen($class) ? " class='".trim($class)."'" : '';33. 34. $output .= "<li$class><a href='$child->url'>$child->title</a>";35. 36. // If this child is itself a parent and not the root page, then render its children in their own menu too...37. if($has_children && $child !== $root) {38. $output .= renderChildrenOf($child->children, $root, $output, $level);39. }40. $output .= '</li>';41. }42. $outerclass = ($level == 1) ? "drop" : '';43. return "<ul id='nav' class='$outerclass'>$output</ul>";44. }45. 46. // bundle up the first level pages and prepend the root home page47. $root = $pages->get(1);48. $pa = $root->children;49. $pa = $pa->prepend($root);50. 51. // Set the ball rolling...52. echo renderChildrenOf($pa);

Here is the footer

58. </div><!-- /content -->59. <div id="footer">60. FOOTER IN HERE61. </div>62. </div><!-- /wrapper -->63. 64. </body>65. </html>

... Which proves the mundane point above.

Here is the CSS

Add this to your TUT_layout.css f ile.

The menu CSS I got f rom somewhere and if I could remember where I wouldthank them f or it ... sorry!

1. #menubar { background-color: #545454; height: 45px; width: 100%; }2. body { background-color: #eee; margin: 0px; padding: 0px; }3. #masthead { background-color: #CCC; height: 150px; width: 100%; }4. #wrapper { background-color: #FFF; width: 1000px; margin-right: auto; margin-left: auto; padding-bottom: 20px; }5. #navbar { height: 45px; width: 1000px; margin-right: auto; margin-left: auto; background: #333; }6. #content { width: 950px; padding-top: 20px; margin-right: auto; margin-bottom: 10px; margin-left: auto; }7. #footer { width: 930px; margin-top: 10px; margin-right: auto; margin-bottom: 10px; margin-left: auto; border: 1px solid #ccc; padding8. #header-banner { margin: auto; width: 1000px; }9. ul#nav { margin: 8px 0 0 20px; }10. ul.drop a { display:block; color: #fff; font-family: Verdana; font-size: 14px; text-decoration: none; }11. ul.drop, ul.drop li, ul.drop ul { list-style: none; margin: 0; padding: 0; color: #fff; }12. ul.drop { position: relative; z-index: 597; float: left; }13. ul.drop li { float: left; line-height: 1.3em; vertical-align: middle; zoom: 1; padding: 5px 10px; }14. ul.drop li.hover, ul.drop li:hover { position: relative; z-index: 599; cursor: default; background: #1e7c9a; }15. ul.drop ul { visibility: hidden; position: absolute; top: 100%; left: 0; z-index: 598; width: 195px; background: #555; border:16. ul.drop ul li { float: none; }17. ul.drop ul ul { top: -2px; left: 100%; }18. ul.drop li:hover > ul { visibility: visible }

At this point we need to check this is at least sort of working!

T esting the layout with the Home page

The best way, f or the moment, is to hijack the original home.php template f ile,since we know that the home page is still using it and it has some content inthe body f ield.

Open home.php and replace its code with this:

1. <?php 2. 3. include("./TUT_header.inc"); 4. 5. echo $page->body;6. 7. include("./TUT_footer.inc");

We are simply including the header and the f ooter and have instructed it tof etch the "body" f ield that is in the "home" template in the administration - thisis why we lef t that f ield intact earlier! A lot of the work you will do inprocesswire once you have played around with your html and css will prettymuch boil down to printing out a f ew f ields. In f act you could probably puttogether a reasonable brochure site without doing much more than that.

Okay, save all that lot and load up the homepage of your site (the root) andhopef ully it will look something like this:

Basic Website Tutorial - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Basic_Website_Tutorial 6 / 35

Page 8: Basic Tutorials for ProcessWire

Recyling Fields

In PW you can reuse f ields on multipletemplates which can save a lot of t imeand makes sense when you haverelated content types or pages thathave similar needs. For instance, youmay want every page, whatever thecontent, to have meta keywords andmeta description that will be added tothe normal site meta. Or, you mayhave a main body that is commonacross several types of articles.

Remember that PW saves f ields intheir own exclusive tables, rather thantrying to squish all the data into asome poor, over used, page f ield.

The trick, theref ore, is f inding thebalance between using the same f ieldbecause you actually want thatcommon data to be all in the sametable, and creating dedicated f ieldsbecause you want the separation ofdata.

When you do reuse a f ield, you arenot stuck with its label and description(and some settings like size). Thesecan be adjusted on a template bytemplate basis, which means you canreuse the f ield while giving it a newlabel, f or instance.

It is worth creating a data policy oncomplicated sites so that you have aconsistent system which may welladdress f uture data integrity andportability issues.

Creating a Site Settings System

All CMSs have a section where youf ill in tons of stuf f about your site -you choose your logo, add a headerbanner, add meta stuf f , a site t it le, aphone number f or everywhere, acontact email address .... every CMShas one of those. They normallyhave exactly the f ields someoneelse thought were usef ul.

Except ProcessWire which holdsonto the philosophy that you maywant to make your own decisionsabout such important things.

So let's go and create one. It wonttake very long and will have exactlywhat we need rather than whatsome developer who has never metus thinks we need. What is more,you can expand it later if you thinkof more things you would like inyour site settings!

Creating the Site

Settings Fields

The f irst step in much of what youwill do in ProcessWire will inevitablybe to create the f ields you will needf or a template.

Go to Setup and then Fields.

The list of f ields that you will see ispretty small, really. But then, this isnot much of a site ... yet!

Click on Add New Field

What ever f ield you are creating,you always start with the same f orm- a Name f or the f ield, the type off ield and the label.

Site T itle

We need a f ield f or our site t it le. So:

Name: site_tit le (no spaces or clever stuf f please)Type: TextLabel: Site T it le

And Save.

Once you have saved you will have lots of dif f erent things you can do withthe f ield. For instance, if you go to the Input tab, you can change theMaxlength, the size and add placeholder text.

Basic Website Tutorial - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Basic_Website_Tutorial 7 / 35

Page 9: Basic Tutorials for ProcessWire

However, f or the moment, lets keep it simple. We have already saved, so goback to Fields in the breadcrumbs at the top of the page.

We need a f ew more f ields:

A banner f or the top of the siteMeta DescriptionFooter text

There are a lot of other things you could add, but that will do f or now.

Meta Keywords and Description

Create a new f ield:

site_meta_description

I am using "site" at the head of all of these just to keep things logical andeasy to f ind.

This should be a textarea and, on the details tab, you may want to set thetext f ormatter to "Html Entit ies" to avoid breaking the meta tag if some extraquotes are added accidentally

Footer T ext

Create a f ield called site_f ooter_text - again, choose a textarea and save.

Once you have saved, go to the Details tab and change the Input f ield Typeto T inyMCE and save.

Now, when you go to the Input tab you can expand an area called T inyMCEAdvanced Conf iguration Options. We don't need to change anything at themoment, but as you can see you can conf igure a dif f erent editorconf iguration f or every single T inyMCE f ield - very usef ul!

Header Banner

The header banner is an image f ield that we want to conf igure just f or thisone job.

Create a new f ield called site_header_banner and choose the Image f ield typeand save.

Under Details, change the Maximum f iles allowed to 1. As you will learn later,the image f ield can upload multiple images and those can then be insertedinto a T inyMCE f ield. What is more, you can loop through those images on atemplate f ile f or a gallery, if you wish! However, we just want the one f or ourbanner at the moment.

Under Input, change the number of rows f or description to zero - we wontneed that in this case.

Display thumbnails in page editor? Why not!

Expand image dimensions and put 1000 f or the width and 150 f or the height.Obviously, in this case we will be uploading a banner the right size, but this isgood practice.

Save.

So, we now have f ive f ields. Next step is to add them to a template.

Creating the Site Settings Template

The Processwire Template system f ulf ils several f unctions.

Firstly and most obviously it groups f ields together to be used f or pagecreation. A template can also be associated with a specif ic template f ile in thetemplates directory. This is a one-to-one relationsship so that a template andits f ile are uniquely bonded together.

However, you can also create a template WITHOUT a template f ile, which isusef ul f or when you are not rendering the f ields out uniquely - and that prettymuch describes what we need f or our Site Settings.

Go to Setup > Templates and click on Add New Template. Depending on whatyou have been playing with you will either get a warning that there were nonew templates f ound or a list of unassociated template f iles it has f ound.Either way, ignore that, and go down to Create a New Template without a f ile.

Fill in the name, "Site-Settings-Template"

Warning: If you put spaces between the words you will get THREE templates;Site, Settings and Template!

You will now see your new template listed and that it has no-f ile, which is agood thing.

Basic Website Tutorial - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Basic_Website_Tutorial 8 / 35

Page 10: Basic Tutorials for ProcessWire

Click on the name to edit the template.

We need to add f ields. It already has a tit le f ield which is needed, so leavethat. Use the drop down to select your f ields one at a t ime.

site_tit lesite_header_bannersite_f ooter_textsite_meta_description

Save.

The template is ready to be used, but we can play with it a bit more f irst.

Go to the Family tab.

"May Pages using this template have children?" No - we only want the one SiteSettings Page. Leave the "Can this template be used for new pages?" to yesf or the moment as we haven't created the page yet. You could change it to nolater.

Save the template and go to the Pages part of the admin.

Creating the Site Settings Page

Select the Home page and click on new. This will create a child page to thehome page.

Give the page the tit le Site Settings and select the Site-Settings-Template.Save.

You will now be presented with the f orm f or your settings. Bef ore you f ill it in,go to the Settings tab.

Check the Hidden checkbox

This will allow us to use the f ields, but will hide the page f rom the menu andso on - so it will be f or back end use only.

Save that (hit the publish button) and go back to the Content.

Fill in the content f ields as you wish. The Site Header Banner should be1000px by 150px, a bit like this subtle one:

Or .. you could use one of your own!

Using the Site Settings

The last step is to grab the data associated with the Site Settings page andput it in the header and f ooter template f iles. In my code above, I have markedwhere you need to put the data in CAPITAL LETTERS. How kind of me!

Go back to your template f iles and open TUT_header.inc.

The instruction we need to give is to f etch the data f rom a page OTHER thanthe one we are on.

$page will ref er to the current page, so $page->body would get the data f romthe body f ield f or the current page.

$pages (plural) together with the GET command will allow us to specif y aparticular page. (See the API f or more details.)

So, this will be the code f or the Meta Description:

1. <?=$pages->get("/site-settings/")->site_meta_description ?>

Note: the php short code (<?=) may not work on your server set up if thathasn't been switched on. If that is the case, use the more usual:

1. <?php echo $pages->get("/site-settings/")->site_meta_description; ?>

You can now use the same method f or f etching the site t it le f or the <tit le>tag (and anywhere else you want it.)

The banner is slightly dif f erent. We need to specif y the URL in this case so

Basic Website Tutorial - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Basic_Website_Tutorial 9 / 35

Page 11: Basic Tutorials for ProcessWire

that we have the f ull path, and put it in an <img> tag, so:

1. <img src="<?=$pages->get("/site-settings/")->site_header_banner->url ?>">

All that is lef t to do is to add the site_f ooter_text to the f ooter, and of f wego!

Adding some Content

The last part of this tutorial is simply about adding some extra content andyou can use it as a bit of a test.

We have some text in our home page, but lets create another page with a newtemplate, just f or the hell of it.

One of the main complaints website administrators have with client controlledcontent is that if you give them too much control, allow them to insert imageslef t right and centre (pun intended), then there is a good chance the site willget broken at some point.

Creating the Article Fields

So, we will create a template that has a main image, an intro text, main textand an optional second image.

That will be f our f ields. However, in addition to the mandatory t it le we will addan optional headline and some keywords that can be added to our metakeyword list.

The headline f ield and tit le f ield already exist in the def ault installation, sohead over to Setup > Fields in the administration and create the f ollowingf ields:

article_introtext - textareaarticle_maintext - textarea/T inyMCE. Note: T inyMCE parameters can beedited on the Input tab. See the article T inyMCE f or more details.article_images - image f ield. Set it f or TWO images (as we will use thisf or both the f irst and second image in the article), no description and280 x 187 size - that is standard landscape proportions f or 35mm (callme old f ashioned). Note: The size parameters are maximum values, sowill only come into play on upload if your image exceeds the sizesettings.article_metadescription - just a text area. However, on the details tab,you may want to set the text f ormatter to "Html Entit ies" to avoidbreaking the meta tag if some extra quotes are added accidentally!

It is worth repeating that you can call your f ields anything you like - I am justusing these names so they are bunched together f or the tutorial. Forinstance, the "body" f ield which is part of the def ault installation, you maywant to use in a lot of settings.

Creating the Article Template File

Go to /sites/templates/ in your installation and create a f ile calledTUT_article.php

This will be the template f ile that we will use f or the template shortly.

First job is to include the header and the f ooter includes of our site, so add:

Basic Website Tutorial - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Basic_Website_Tutorial 10 / 35

Page 12: Basic Tutorials for ProcessWire

1. <?php include("./TUT_header.inc"); ?>2. 3. <?php include("./TUT_footer.inc"); ?>

Remembering that our content box in our site template structure is 950pxwide, we might as well make good use of it.

You can do whatever layout you wish, really. There are six f ields to play within the structure:

tit leheadlinearticle_mainimagearticle_introtextarticle_images

In my layout I am putting the f irst image next to the tit le/headline (just one orthe other) and the intro text, then put the main text on another row with thesecond image f loated.

This is my starting layout:

2. <div id="article-container">3. <div class="article-row">4. <div class="article-mainimage"></div>5. <div class="article-introbox">6. <div class="article-introtext">7. </div>8. </div>9. </div>10. <div class="article-row">11. <div class="article-main clearfix"></div>12. </div>13. </div>

And I am adding the f ollowing rather rough and ready CSS to theTUT_layout.css f ile:

51. #article-container {52. width: 950px;53. }54. .article-row {55. clear: both;56. }57. .article-mainimage {58. float: left;59. width: 280px;60. padding: 20px;61. border: 1px solid #ccc;62. }63. .article-introbox {64. float: right;65. width: 580px;66. margin-right: 20px;67. margin-top: 40px;68. min-height: 234px;69. }70. .article-introbox h2 {71. text-align: center;72. }73. .article-introtext {74. font-style: italic;75. }76. .article-main {77. margin-top: 20px;78. }79. .article-main img {80. float: right;81. margin: 20px;82. }83. .clearfix:after {84. content: ".";85. display: block;86. clear: both;87. visibility: hidden;88. line-height: 0;89. height: 0;90. }91. 92. .clearfix {93. display: inline-block;94. }95. 96. html[xmlns] .clearfix {97. display: block;98. }99. 100. * html .clearfix {101. height: 1%;102. }

Adding the Fields

Although the template is yet to be created in the admin, we already have thef ields, so might as well add them.

Just a reminder that ProcessWire spits everything out without any f ormatting,so we should add some; admittedly, nothing exactly taxing! For these calls weuse $page, since we are wanting f ields related to the current page. Forinstance, <?=$page->tit le ?> will add the tit le f ield (or <?php echo $page->tit le; ?> will do the same thing).

As with our header banner earlier, the images will need the additional ->url onthe end to get the f ull path.

And there is a neat trick f or the tit le: $page->get("headline|tit le")

In this statement, we are asking f or two alternatives and will return the f irstone that has a value. If we have put text in the headline f ield, then that is whatwill be returned. If no text is in the headline f ield, then the mandatory t it le f ieldvalue will be returned. Usef ul and simple - my kind of programming (Thanks,Ryan).

However, we need to do something clever with out images. In our f ield we areuploading two images. So, when we retrieve our image URL, we need tospecif y the f irst() image and the last() image. This means that if we changethe order of our images in the admin (you can drag and drop them) they willchange order on the page.

So, this is what I have so f ar:

Basic Website Tutorial - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Basic_Website_Tutorial 11 / 35

Page 13: Basic Tutorials for ProcessWire

Restricting Content Types

The good thing about this system isthat you use the same procedure tocreate ANY type of content. The typeof content is simply decided byf orcing you to choose a template. Youcan also limit what templates areavailable by settings within thetemplates themselves - you can

1. <?php include("./TUT_header.inc"); ?>2. 3. <div id="article-container">4. <div class="article-row">5. <div class="article-mainimage">6. <img src="<?=$page->article_images->first()->url ?>">7. </div>8. <div class="article-introbox">9. <h2><?=$page->get("headline|title") ?></h2>10. <div class="article-introtext">11. <?=$page->article_introtext ?>12. </div>13. </div>14. </div>15. <div class="article-row">16. <div class="article-main">17. <img src="<?=$page->article_images->last()->url ?>">18. <?=$page->article_maintext ?> 19. </div>20. </div>21. </div>22. 23. <?php include("./TUT_footer.inc"); ?>

Creating a Template

The next step is to create the actual template. Go into your ProcessWireadmin and to to Setup > Templates. Click on Add New Template.

This t ime, the system should have spotted our article template f ile:

Simply check the box and click on add template. You will see it in the list.

Click on the TUT_article to open it.

Add all the article_ f ields you created plus the headline f ield. The tit le f ield isalready there. Don't f orget the article_metadescription, even though wehaven't used it yet.

Save

You can reorder the f ields however you wish by grabbing and moving thef ields up and down. This uses a special select f ield called asmSelect which isavailable as an option f or the Page Field Type.

Creating an Article

The template f ile is done (may need some messing with), the f ields are madeand the template is created. The only thing to do is to create a page and try itout

Go to Pages.

Click on "new" by the Home page - we might as well make it a direct child.

Give the page a tit le - My Article

Select the TUT_article template. AndSave.

You will now be presented with yourf orm.#

Well, dont just sit there! Stuf f it withthings!

Once you have entered content ofyour choice, there is one more bit of

Basic Website Tutorial - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Basic_Website_Tutorial 12 / 35

Page 14: Basic Tutorials for ProcessWire

decide that a Child of a page thatuses a particular template can onlyuse one of a specif ied list oftemplates. That makes the systemvery customisable and neat f orclients. They cannot choose thewrong template f or the wrong part ofyour menu if you don't let them.

Some more text

edit ing that needs to be done.

Go back to your template f iles andopen TUT_header.inc.

In the Meta Keywords section, addyour new article keywords f ield likethis:

<meta name="description" content="<?=$pages->get("/site-settings/")->site_meta_description ?>, <?=$page->article_metadescription ?>">

If you add the article_metadescription f ield to ANY template and f ill it in f orany page, then you will have custom, relevant keywords in addition to yourglobal keywords. Even though this code is in the header include f ile, it will takethe value f rom the CURRENT page, because that is what we have told it todo.

So. Fire up your page!

Just one litt le job. You will notice that the site map is still using the old def aulttemplate.

Open sitemap.php and change the head and f oot includes to your newTUT_header.inc and TUT_f ooter.inc. That should sort that out.

Conclusion

The basic site now works.

You have a simple site settings system that will control some basicelements of the site which you can expandYou have created your own header and f ooterYou have created specif ic f ields f or your needsYou have created specif ic templates f or your needsYou have learned how to f etch data into your templatesYou have created pages using your own templatesYou have added a particularly crass header image - unless you weresensible enough to make your own!

At this point, you could create an okay brochure site without doing much moreand it would be very quick to do.

However, there is much more than can be done with ProcessWire. Furthertutorials will cover common tasks like creating a slide show, adding a lightboxsystem f or images, creating a basic news system and so on.

See Also

Basic Website Tutorial - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Basic_Website_Tutorial 13 / 35

Page 15: Basic Tutorials for ProcessWire

Privacy policy About ProcessWire Disclaimers

This page was last modified on 24 March 2013, at 12:32.

This page has been accessed 2,451 times.

Simple News SystemSimple Gallery System

Categories: Long Tutorials Pending

Basic Website Tutorial - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Basic_Website_Tutorial 14 / 35

Page 16: Basic Tutorials for ProcessWire

Simple News System

Contents [hide]

1 What You Will Learn

2 How the system is st ructured2.1 Hidden Pages2.2 Template Files and Functions

3 Creat ing the Files

4 Fields and Templates4.1 Templates

4.1.1 Parent Pages4.2 Fields

4.2.1 Article Thumbnails4.2.2 Article Category

4.3 Adding Fields to Templates

5 Creat ing Categories

6 Creat ing News

7 The Template Files and Funct ions7.1 Function newsList()

7.1.1 Function categoriesList()7.1.2 Funtion newsDisplay()

7.2 Finishing the Template Files7.2.1 TUT_news_index.php7.2.2 TUT_news.php

8 Finishing Of f

9 See Also

This Article Stub is work in progress!

It may contain inf ormation that is incomplete or needs testing

This tutorial looks at one simpleway of creating a basic news orblog system f or a ProcessWirewebsite. It will help you createcategories, basic articles and anews index page. This is not adef init ive way of handling news,but is a very straightf orward onewhich you can adapt as you wish.

The tutorial uses the BasicWebsite Tutorial as a startingpoint and reuses some of thef ields and design f rom that tutorial,though the techniquesdemonstrated can easily be copiedinto any ProcessWire website.

What You Will Learn

How to use Page f ields and pagesf or categoriesHow to list pages that are indif f erent parts of the page treeHow to use the Thumbnails module(in its basic f orm)How to use f unctions to simplif yyour template f ile structure

If you are new to ProcessWire I strongly suggest you do the Basic WebsiteTutorial f irst as this will give you the basic working model f or this tutorial andwill teach you much of the basic techniques of using the system. It only takesabout half and hour or so to do.

Read View source View history Go Search

Log in

Page Discussion

Navig atio n

Main pageRecent changesRandom pageArticle help

Pro cesswire

HomepageDownloadsForums

T o o lbo x

What links hereRelated changesSpecial pagesPrintable versionPermanent link

Simple News System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_News_System 15 / 35

Page 17: Basic Tutorials for ProcessWire

How the system is structured

Generally speaking, a basic site in ProcessWire is structured using theparent/child relationship that makes up the page tree. This is a very neat andordered way of using ProcessWire and is the basis f or both simple sites andhuge, complicated sites.

However, it is sometimes expedient to store inf ormation in a slightly dif f erentway simply because you want to handle it dif f erently. News articles are a goodexample of this; you would normally expect there to be a lot of them and f orthem to be categorised in some way that is not immediately suitable f or orref lects a site's menu.

In such as circumstance, it is possible to store them in the page tree in such away that they are not directly available via the menu.

Hidden Pages

Under the settings tab of the page edit dialogue, a page can be set to"hidden." This does not un-publish the page, but simply stops it appearing inthe f ront menu or any system that automatically lists the children of anotherpage.

In addition to hiding the page itself , any children of that page are also hidden,whether they are individually set as hidden or not.

We can use this to our advantage by creating a hidden "New Articles" pageand hidden "Categories" page under which we can store our categories andarticles.

Template Files and Functions

The system uses two template f iles (plus two templates without f iles) and af unctions f ile that will hold most of the rendering f or articles and lists.

Using f unctions in this way in a combined f ile means the template f iles arekept very much simpler, helping any f uture structural changes, and it allowsthe f unctions to be reused in dif f erent templates if required.

Creating the Files

We require three f iles f or this particular system.

Navigate to /site/templates/ and create these f iles:

TUT_news.phpTUT_news_index.phpTUT_news_f unctions.inc

Simple News System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_News_System 16 / 35

Page 18: Basic Tutorials for ProcessWire

Note: the use of TUT is simply so that these tutorial f iles match the onesused in the other related tutorials - you can, of course, name the f ileswhatever you wish!

Open up the two php f iles - these will be our template f iles.

For the moment we only need to include the header and f ooter f iles intothese and also our new f unctions f ile.

Add the f ollowing to the two php f iles:

1. <?php2. include("./TUT_header.inc"); 3. include("./TUT_news_functions.inc");4. 5. include("./TUT_footer.inc");

Save and close the f iles, we will return to them shortly.

Fields and Templates

Go to the administration of your website.

We need to create some f ields, some templates and a couple of pages. Wewill start with the templates.

Templates

Go to Setup > Templates and click on New Template.

You will see the two php f iles f rom earlier listed. Check the box f or each andclick on the Add Templates button.

That gives us the templates f or the news index page and f or the actual newsarticles.

We need to create two templates that do not have f iles to be used f or thehidden pages that will beccome the parents f or the news articles and thecategories.

In Setup > Templates click on Add New Template. It should say that no newtemplate f iles were f ound. Go to Create a new template without a f ile.

Enter:

categories news-articles

making sure that there is a space between the two. This will create twotemplates. Click Add Templates.

Simple News System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_News_System 17 / 35

Page 19: Basic Tutorials for ProcessWire

The reason we have created specif ic templates at this point is that we wantto set our pages to work in a very particular way. Click on the categoriestemplate to edit it.

Go to the f amilies tab and open the allowed templates f or children. From thedropdown, select "TUT_news_index." When you create a new child to thecategories page later, you will only be able to use this template f or the childpage.

Save and close the template.

Now edit the news-articles template. Under the f amilies tab selectTUT_News as the allowed template f or children.

Save and Close the template.

Bef ore we carry on, we will need the category parent page in place, so let uscreate that and the article parent page and news page while we are at it.

Parent Pages

Go to pages, select the home page and click on new page to create a newchild page.

Call it News Articles and select the news-articles template. Save.

Go to the settings tab and make the page hidden but published and save.

Close and create another page under Home.

Call this one Categories and select the categories template. Save.

Go to the settings tab and make the page hidden but published, then save.

Return to the pages menu, create a third page under home, and call it News.

Select the news-index template and save and publish. Close the page. Thiswill be our news page on the f ront of the site.

Fields

We can now return to sorting out our f ields and templates.

You will need to create the f ollowing f ields (some are already created if youhave done the Basic Website Tutorial):

T it le - this f ield already exists.article_introtext - textarea f ieldarticle_maintext - textarea/tinymce f ieldarticle_thumbnails - a Crop Image f ield (see below)article_category - a Page f ield (see below)

Title obviously exists already, the next two are f rom the Basic Website

Simple News System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_News_System 18 / 35

Page 20: Basic Tutorials for ProcessWire

tutorial - they do not require anything special.

Article T humbnails

This is a special f ield using the Thumbnails Module. See Here if you have notalready installed it.

Create a new f ield, call it article_thumbnails and choose the Cropimage f ieldtype (this is the thumbnails f ield type).

Give it a label of Article Main Image.

Save the f ield then go to the Details tab and add "1" to maximum f iles allowed.

On the input f ield open Max image dimensions and enter 1000 f or the widthand 669 f or the height. Normal camera proportions.

Under Thumnail settings, enter the f ollowing:

thumbnail,360,280 listingthumb,280,170

Save the f ield.

Although the normal images f ield allows you to set image sizes on the f ly inthe template f iles and will cache that image size in the assets f older, theThumbnails module also allows basic cropping of the images to f it specif icthumbnail sizes, which is very usef ul! However, it requires the image sizes tobe set in advance rather than on the f ly f or this to work.

Article Category

This is a page f ield, which allows one or more pages to be selected f rom apredetermined set of parameters.

Create a f ield called article_category and choose the page f ield type. Give it alabel of Category and save.

In the Details tab, set it to single - the third option.

In the Input tab, change the parent to your Categories page that we createdearlier. This means that only the children of the category page will be listed.

Leave the input f ield type as Select, then Save.

Adding Fields to Templates

Fields only need to be added to two templates - TUT_news andTUT_news_index.

For TUT_news_index, simply add the article_maintext f ield. This will just beused f or a short, optional introduction to the main news page and thecategory pages.

Simple News System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_News_System 19 / 35

Page 21: Basic Tutorials for ProcessWire

For TUT_news, add all the f ields f rom above:

article_categoryarticle_introtextarticle_maintextarticle_thumbnailsarticle_metadescription

Creating Categories

Bef ore we create some news and then work on the template f iles, we willneed some categories.

Go to pages and select the hidden Categories page.

Click on new page.

You should f ind that you are not given a template option - that has beenpreselected as TUT_news_index

Give your category a tit le and save.

Optionally, add some maintext - this will just be an introductory description f orthe category,.

Publish.

Create a couple more categories in the same way.

Creating News

Although we have no way of displaying the articles yet, we can add somenews anyway while we are here.

On the Pages section, select the hidden page News Articles and create a newpage.

As with categories, the template will be preselected - in this case TUT_news.

Create a handf ul of articles, remembering to choose a category f or each (Youmay wish to set the category f ield as required on the template)

The Template Files and Functions

Most of the work of displaying the articles will be done by theTUT_news_f unctions.inc f ile. The two template f iles TUT_news_index.phpand TUT_news.php will simply render the f unctions within the header/f ooter

Simple News System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_News_System 20 / 35

Page 22: Basic Tutorials for ProcessWire

template f ramework.

Function newsList()

This f unction is the most complicated of the three f unctions needed f or thenews system.

Firstly, the f unction gets the name of the current page and checks to see if itis called "news." News is our main news page and will list all recent articles.

However, if it is NOT called news, that means it is one of our category pages,and we will only want to show items that are related to that catgegory.

We then use f ind() to retrieve all pages where the parent is news-articles, thetemplate is TUT_news and if it is a category page, by the name of thecategory too.

Af ter that, we loop through the results and print out the articles.

At the bottom of the f unction, we print out some pagination.

Here is the f unction:

/* LIST ARTICLES This displays a list of articles in div containers on the news-index page. */ function newsList(){ // Grab the page name from the url $thisCategory = wire("page")->name; // If the category is not called "news" then output the category name as a selector for the find. if($thisCategory !="news") { $category = "article_category.name=" . $thisCategory; } // Get the news posts - limited to ten for later pagination $newsposts = wire("pages")->find("parent=/news-articles/, $category, template=TUT_news, limit=10" $out =" "; //Loop through the pages foreach($newsposts as $newspost){ $out .="<div class='clearfix'>"; if($newspost->article_thumbnails){ $out .="<a href='{$newspost->article_thumbnails->url}' class=''>"; $out .="<img class='align_left' src='{$newspost->article_thumbnails $out .="</a>"; } $out .="<a href='{$newspost->url}'><h3>{$newspost->title}</h3></a>"; $out .="<p>{$newspost->article_introtext}</p>"; $out .="</div>"; } // Pagination

Notice the use of wire("pages") rather than $pages? This is because we areworking within a f unction and $pages would not be understood inside af unction.

The pagination used the same $newsposts variable as the f oreach loop andso the number of items shown on each page will be set by the limit value onthe init ial "f ind" statement.

Function categoriesList()

On the same page, we also want to list our categories.

Simple News System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_News_System 21 / 35

Page 23: Basic Tutorials for ProcessWire

This is simply a case of f inding the pages where the parent is categories, andthe template is TUT_news_index and sort them alphabetically.

We can then loop through them and use their URL to link to them. This URLwill, of course use this current template f ile, so we will, in ef f ect be returninghere, but with a dif f erent page name - and that def ines our category!

Here is the code:

/* CATEGORIES LIST This lists available categories */ function categoriesList(){ $categories = wire("pages")->find("parent=/categories/, template=TUT_news_index, sort=title" $out =" "; foreach($categories as $category){ $out .="<li><a href='{$category->url}'>{$category->title}</a></li>"; } echo "<ul>$out</ul>"; }

Those two f unctions will both appear on the TUT_news_index.php templatef ile. This template f ile is used both f or the main news and the categories.

Funtion newsDisplay()

This very short f unction just displays the entire article.

Obviously, as with the other f unctions, you would customise this dependingon how you want the article to be displayed.

/* DISPLAY ARTICLE This displays the article on the news page. You can change the <a> class if you are using a lightbox*/ function newsDisplay(){ $newspost = wire("page"); $out =" "; if($newspost->article_thumbnails){ $out .="<a href='{$newspost->article_thumbnails->url}' class=''>"; $out .="<img class='align_right' src='{$newspost->article_thumbnails $out .="</a>"; } $out .="<h2>{$newspost->title}</h2>"; $out .=$newspost->article_maintext; echo "<div class='clearfix'>$out</div>";}

Simple News System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_News_System 22 / 35

Page 24: Basic Tutorials for ProcessWire

These three f unctions should be put in the TUT_news_f unctions.inc f ilewithin PHP tags. This f ile should be included at the head ofTUT_news_index.php and TUT_news.php

Finishing the Template Files

T UT _news_index.php

Edit the TUT_news_index.php f ile and add the categoriesList() and newsList()f unctions where you wish. For example:

include("./TUT_header.inc"); include("./TUT_news_functions.inc"); // Give the news index page a title an a bit of an intro echo "<h1>{$page->title}</h1>"; echo $page->body; // Render the Category List categoriesList(); // Render the News List newsList(); include("./TUT_footer.inc");

T UT _news.php

Edit TUT_news.php and add the newsDisplay() f unction:

include("./TUT_header.inc"); include("./TUT_news_functions.inc"); // Output the newsDisplay function newsDisplay(); include("./TUT_footer.inc");

Finishing Off

The very simple news system should now be working.

All that will remain is f or you to style it to suit your needs.

You could also extend this using more f ields, creating variations on listing f orside bar recent news lists and so on, using broadly the same principles.

As you will realise, the explanation may be quite long, but the actual code

Simple News System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_News_System 23 / 35

Page 25: Basic Tutorials for ProcessWire

Privacy policy About ProcessWire Disclaimers

This page was last modified on 25 March 2013, at 04:54.

This page has been accessed 418 times.

involved is minimal - the PW core is doing all the heavy lif t ing allowing you thef reedom to create this small application however you want.

See Also

Basic Website TutorialSimple Gallery System

Categories: Long Tutorials Draf ts

Simple News System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_News_System 24 / 35

Page 26: Basic Tutorials for ProcessWire

Simple Gallery System

Contents [hide]

1 What You Will Learn

2 Preparat ion2.1 Installing JQuery and Plugins2.2 Functions file

3 Templates and Fields3.1 Template Files3.2 Templates3.3 Fields

3.3.1 Gallery3.3.2 gallery_thumbnail_size

3.4 Add the fields to the templates

4 Creat ing Content

5 The Funct ions5.1 Function albumList()5.2 Function infoDisplay()5.3 Function albumGrid()5.4 Function albumShow()

6 Adding funct ions to the Template Files6.1 TUT_gallery_index.php6.2 TUT_gallery.php

7 JQuery and Finishing

8 See Also

This Article Stub is work in progress!

It may contain inf ormation that is incomplete or needs testing

This tutorial looks at onesimple way of creating abasic gallery system f or aProcessWire website. It willshow how to install a 3rdparty JQuery plugin(FlexSlider) to display agallery and a lightbox, how todisplay a page of thumbnailsand how to create theassociated Gallery/Album inProcessWire

The tutorial uses the BasicWebsite Tutorial as astarting point and reusessome of the f ields anddesign f rom that tutorial,though the techniquesdemonstrated can easily becopied into any ProcessWirewebsite.

It also uses very similarf unctionality to the SimpleNews Tutorial

What You Will

Learn

Using the Image f ield type f or multiple imagesUsing the built in image size system and making it customisable f romthe back end

Read View source View history Go Search

Log in

Page Discussion

Navig atio n

Main pageRecent changesRandom pageArticle help

Pro cesswire

HomepageDownloadsForums

T o o lbo x

What links hereRelated changesSpecial pagesPrintable versionPermanent link

Simple Gallery System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_Gallery_System 25 / 35

Page 27: Basic Tutorials for ProcessWire

Installing and using 3rd party JQuery PluginCreating f unctions to display the various components.

Preparation

I will be starting with the Basic Website Tutorial and using the same f ile andf ield naming conventions as I did there. But remember, that this is only onepossibly way of creating a gallery and you can call templates and f ieldswhatever you wish!

The two plugins required are Colorbox and Flexslider 2 and we will alsorequire an up-to-date version of JQuery. As of the writ ing of this tutorial, thatis version 1.9.1

Installing JQuery and Plugins

Download JQuery and copy it to /site/templates/scripts/ f older.

Download Colorbox. Copy jquery.colorbox-min.js to the scripts f older andcolorbox.css to the /site/templates/styles/ f older.

Download Flexslider. Copy jquery.f lexslider-min.js to the scripts f older andf lexslider.css to the /site/templates/styles/ f older.

Create a new f ile in the scripts directory and call it TUT.js - we will use this f oradditional JQuery where required.

Open your f ooter include f ile in /site/templates/. If you are using the BasicTutorial setup, this f ile is called TUT_f ooter.inc

Add the f ollowing script ref erences:

1. </div><!-- /content -->2. <div id="footer">3. <?=$pages->get("/site-settings/")->site_footer_text ?>4. </div>5. </div><!-- /wrapper -->6. 7. <script type="text/javascript" src="<?php echo $config->urls->templates?>js/jquery-1.9.1.min.js">8. <script type="text/javascript" src="<?php echo $config->urls->templates?>js/jquery.colorbox-min.js">9. <script type="text/javascript" src="<?php echo $config->urls->templates?>js/jquery.flexslider-min.js">10. <script type="text/javascript" src="<?php echo $config->urls->templates?>js/TUT.js">11. 12. </body>13. </html>

It is important the the TUT.js is last as this will be used f or any conf igurationrelated to the other plugins, and theref ore they must be loaded and available.

Open your header include - if you are using the Basic Tutorial setup, this f ileis TUT_header.inc

Simple Gallery System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_Gallery_System 26 / 35

Page 28: Basic Tutorials for ProcessWire

Add the two links to the colorbox css and f lexslider css

1. <head>2. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"3. <meta name="description" content="<?=$pages->get("/site-settings/")->site_meta_description ?>">4. <title><?=$pages->get("/site-settings/")->site_title ?></title>5. <link rel="stylesheet" type="text/css" href="<?php echo $config->6. <link rel="stylesheet" type="text/css" href="<?php echo $config->7. <link rel="stylesheet" type="text/css" href="<?php echo $config->8. </head>

You have now installed JQuery and the two required plugins.

Functions file

As with the Simple News System I will use a f unctions f ile to create simplef unctions and then just import those into the templates.

Create a new f ile in /site/templates/ called TUT_gallery_f unctions.inc

If you have done the Simple News System tutorial you will have alreadycreated a f ile called TUT_news_f unctions. In a proper site you would probablycombine f unctions together in one large f ile and include it on each template.However, f or the sake of keeping these tutorials uncluttered, I will use af unctions f ile f or each system.

Templates and Fields

Just like the Simple News System, I am using three templates, two of whichhave associated template f iles.

Template Files

In /site/templates/ create two f iles TUT_gallery_index.php andTUT_gallery.php

Add the f ollowing code to each which just includes the header, f ooter and thef unctions f ile:

1. <?php2. include("./TUT_header.inc"); 3. include("./TUT_gallery_functions.inc");4. 5. include("./TUT_footer.inc");

Save those f iles and logon to the backend of you ProcessWire site.

Simple Gallery System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_Gallery_System 27 / 35

Page 29: Basic Tutorials for ProcessWire

Templates

Go to Setup > Templates and click on Create New Template.

Your two template f iles should be shown - check the boxes next to each andclick Save.

Edit the TUT_gallery_index template, go to the URLs tab and switch on UsePage numbers - this will be needed f or pagination. Save and close.

Click on Create New Template again.

This t ime go to Create New Template without a f ile. Call the template albums.Save.

Click on the album template to edit it and go to the Family tab. Open the f ield"Allowed templates f or children" and select the TUT_gallery template.

This template will be used as the parent f or all the albums in the gallery. Youwill note that this is the same procedure as f or the Simple News System, ifyou have completed that tutorial.

Once you have saved the template, go to Pages and create a new page as achild of Home. Call it albums, select the albums template and save. Now, go tothe settings tab and set this page as Hidden. Save and return to Pages.

Create a new page as a child of home. Call it Gallery and select theTUT_gallery_index template. Save.

Fields

We will only require f our f ields f or this system - two of which already exist inthe original Basic tutorial.

gallery - this is a standard image f ieldgallery_thumbnail_size - this is an integer f ieldtit le - this is the standard tit le f ield that is already available inProcessWirearticle_maintext - this is a Textarea/T inyMCE f ield. If you have not donethe previous tutorials, simply use the body f ield and substitute it intothe rest of the code.

Gallery

Go to Setup > Fields and create a new f ield.

Call it gallery and select the image f ield type. Save.

Under the details tab, the number of images can either be limited (16 or 20 orsomething) or lef t as 0 f or any number. However, f or a gallery, it probablyshould be more than 1!

Simple Gallery System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_Gallery_System 28 / 35

Page 30: Basic Tutorials for ProcessWire

Under the Input tab, scroll down and set the max width f or 1000 and theheight f or 669 (35mm dimensions). Set the description rows f or whatever youlike (1 is normally f ine) and select the Show Thumbnails checkbox.

Save and close.

gallery_thumbnail_size

This f ield will be used in part of the demo to set the size of the thumbnails assquares.

Create a new f ield and call it gallery_thumbnail_size. Select the int type, give ita usef ul Label like Thumbnail Size and save.

You can set minimum and maximum values f or the f ield - I have used 100 and300.

Add the fields to the templates

Add article_maintext (or the body f ield) to both TUT_gallery_index andTUT_gallery.

Add the gallery f ield and gallery_thumbnail_size to the TUT_gallery template.

That is all that will be required f or this system to work.

Creating Content

Bef ore moving onto the template f iles and the f unctions, creating content willgive something to work with.

Go to the Gallery page you created earlier and go into edit.

There are only two f ields available here - t it le, which is already completed, andarticle_maintext (or body if you are using that).

In article_maintext, just add a f ew lines to introduce your overall gallery, thensave.

Now go to the hidden "albums" page you created earlier and create a newchild page. This new page should have the TUT_gallery template already sincewe set that up by limiting which template the children of the albums page canuse.

Give the new page a tit le and save. Then add some introductory text and aselection of images - say around 12. Keep the introductory text short as f orsimplicity we are using this text both on the main album page and on thegallery listing page. Finish by entering a width into the thumbnail width box -150, perhaps.

Save this page and close. If you wished, you could add several albums, but

Simple Gallery System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_Gallery_System 29 / 35

Page 31: Basic Tutorials for ProcessWire

one will be enough f or the moment.

The Functions

The f unctions f or the gallery will all be coded into TUT_gallery_f unctions.inc.They are:

inf oDisplay() - this is just the intro text and tit le of the albumalbumGrid() - this will just be a grid or list of thumbnailsalbumShow() - This is the slide show with carousel using the sameimagesalbumList() - this is the list of albums that is shown on the gallery indexpage.

Function albumList()

I will start with the albumList() f unction. If you have completed the SimpleNews System tutorial, this f unciton should look very f amiliar to you as I wrotea similar f unction f or listing the news articles.

Actually, all I have done here is to remove the category ref erences andchanged the name of the variables to better suit out purposes here.

There is another dif f erence that should be noted, however. With the newssystem, I used the Thumbnail module, the cropimage f ield type. Here I haveused the normal image f ield, do rather than f etch a thumbnail, I have specif ieda size(280). This will create a cached version of the image to the sizespecif ied.

Here is the code.

1. function albumList(){2. 3. // Get the list of albums - limited to ten for later pagination4. 5. $albums = wire("pages")->find("parent=/albums/, template=TUT_gallery, limit=10"6. 7. $out =" ";8. 9. //Loop through the pages10. 11. foreach($albums as $album){12. $out .="<div class='clearfix'>";13. if($album->gallery){14. $out .="<img class='align_left' src='{$album->gallery->first()->size(280)->url}'>"15. }16. $out .="<a href='{$album->url}'><h3>{$album->title}</h3></a>";17. $out .="<p>{$album->article_maintext}</p>";18. $out .="</div>";19. 20. }21. // Pagination22. 23. $out .="<div class='pagination'>";The code is very simple.

Simple Gallery System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_Gallery_System 30 / 35

Page 32: Basic Tutorials for ProcessWire

The code is very simple.

We start by using the search expression "f ind" to f ind all pages where theparent is the page albums and the template is TUT_gallery and we are limitingour search to 10. This limit will be used by the Pager to paginate af ter 10entries.

Having stored our album pages in a variable called $albums, we then iteratethrough it using a f oreach loop and print out our album tit les, f irst image andarticle_maintext.

Note: notice the use of "f irst()" in the <img line. Since our images f ield hasseveral images associated with it, it returns an array (if we had set it to onlyallow 1 image, it would return that image and not an array). We can use f irst()to return just the f irst image f rom the array, which will suit our purposes here.If you change the order of the images when editing the page, you can changewhich image will be f irst in the array.

Finally, we use the Pager ref erenced to the $albums variable to print out ourpagination.

Copy the code f rom above and paste it into TUT_gallery_f unctions.inc,remembering to start with <?php!

Function infoDisplay()

This f unction is a t iny f unction that just returns the tit le and article_maintextf or the top of the album and the gallery index page. It is probably slightlyoverkill to do this in this way, but it keeps with the theme!

All that is happening is that we are getting the tit le and the article_maintextand wrapping them up in a div.

Copy the f ollowing into your TUT_gallery_f untions.inc f ile:

37. function infoDisplay(){38. $info = wire("page");39. 40. $out =" ";41. $out .="<h2>{$info->title}</h2>";42. $out .=$info->article_maintext;43. 44. echo "<div class='clearfix'>$out</div>";45. }

Function albumGrid()

This f unction simply returns the list of images f rom our gallery, shoves eachin a DIV and links a thumbnail to the f ull size image, displayed in a lightbox.

For this we are going to use the gallery_thumbnail_size f ield value to dictatehow big our thumbnails are. Here is the code:

Simple Gallery System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_Gallery_System 31 / 35

Page 33: Basic Tutorials for ProcessWire

46. function albumGrid() {47. $albumimages = wire("page")->gallery;48. $thumbsize = wire("page")->gallery_thumbnail_size;49. $out = " ";50. 51. foreach ($albumimages as $albumimage) {52. 53. $out .= "<a href='{$albumimage->url}' title='{$albumimage->description}54. $out .= "<img src='{$albumimage->size($thumbsize, $thumbsize55. $out .= "</a>";56. 57. }58. 59. echo "<div class='albumgrid'>{$out}</div>";60. }

First of all we get the array in our gallery f ield and put it into a variable called$albumimages.

Next we get the value of our thumbnail size and put it into a variable called$thumbsize.

Af ter that we loop through the array, outputting the images and f inish bywrapping it all up in a div.

Notice that on the <img> line, we are using our $thumbsize variable to dictatethe size of the thumbnail. It is written twice f or width and height - so thesethumbnails will be square.

Also, in the <a> tag that wraps around the image, I have added the class"colorbox" and the rel attribute with a value of group. This is f or the colorboxlightbox plugin f rom Jack Moore which we will init ialise later in TUT.js. I havealso returned the description part of the image f or the "tit le" attribute - if youf ill in descriptions f or the images, they will appear on the modal.

Paste the above code into TUT_gallery_f unctions.inc

Function albumShow()

This last f unction is f or displaying the image array in a slideshow withaccompanying carousel. This is using the Flexslider 2 plugin f rom WooThemes.

This f unction has two main parts - the slideshow and the carousel. Inaddition, we are using the description f rom the images underneath theslideshow. Here is the code:

61. function albumShow() {62. 63. $albumimages = wire("page")->gallery;64. $thumbsize = wire("page")->gallery_thumbail_size;65. 66. $out =" ";

Simple Gallery System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_Gallery_System 32 / 35

Page 34: Basic Tutorials for ProcessWire

67. // Slides68. $out .="<div id='gallery-slider' class='flexslider'><ul class='slides'>"69. foreach ($albumimages as $albumimage) {70. $out .="<li>";71. $out .="<img src='{$albumimage->url}'>";72. $out .="<div class='gallery-caption'>{$albumimage->description}73. $out .="</li>";74. }75. $out .="</ul></div>";76. // Carousel77. $out .="<div id='gallery-carousel' class='flexslider'><ul class='slides'>"78. foreach ($albumimages as $albumimage) {79. $out .="<li>";80. $out .="<img src='{$albumimage->size($thumbsize, $thumbsize)->url}'>"81. $out .="</li>";82. }83. $out .="</ul></div>";84. echo $out;85. }

As with the grid, we f irst get the images array and the value f rom thethumbnail size f ield.

We run two loops, once f or the slides and one f or the carousel. The DIV id'sand classes are important here as they relate directly to the JQuery we willuse shortly.

Aside f rom the f act that these use unordered lists, these loops are prettymuch the same as used f or the grid f unction.

Paste this code into the TUT_gallery_f unctions.inc f ile and save it.

Adding functions to the Template Files

All that remains is to add the f unctions to the two template f iles.

TUT_gallery_index.php

Open the gallery index php f ile and add two f unctions - inf oDisplay() andalbumList().

Your f inal f ile should look like this:

1. <?php 2. 3. include("./TUT_header.inc"); 4. include("./TUT_gallery_functions.inc");5. 6. // Give the news index page a title an a bit of an intro7. 8. infoDisplay();9. 10. // Render the Album List11. 12. albumList();13. 14. include("./TUT_footer.inc");

We have included the header, then the f unctions f ile, added the two f unctions

Simple Gallery System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_Gallery_System 33 / 35

Page 35: Basic Tutorials for ProcessWire

and then the f ooter. Save the f ile.

TUT_gallery.php

For the hell of it, we will put both the grid display of the album images and theSlideshow with carousel all on the same page - just so we know it works.

1. <?php 2. 3. include("./TUT_header.inc"); 4. include("./TUT_gallery_functions.inc");5. 6. // Output the albumDisplay function7. 8. infoDisplay();9. 10. // Out put the album grid11. 12. albumGrid();13. 14. albumShow();15. 16. include("./TUT_footer.inc");

As you can see, it looks pretty much like the gallery index f ile. This is one ofthe advantages of using f unctions in this way - the template f iles are verymuch simplif ied, basically sticking with the major structural layout of the pageor site, while the f unctions take care of the logic and minutiae.

JQuery and Finishing

That is more or less that. However, the two JQuery plugins that are beingused need to be init ialised.

Open TUT.js and add the f ollowing code:

1. jQuery(document).ready(function($){2. 3. // Initialize colorbox4. jQuery('a.colorbox').colorbox({ 5. opacity:0.3 ,6. speed: 500,7. transition: "elastic",8. slideshow: false, 9. rel:'group',10. previous:"<span class='colorboxnav'><</span>",11. next:"<span class='colorboxnav'>></span>",12. close:"<span class='colorboxnav'>X</span>",13. maxHeight: "90%"14. 15. })16. 17. // Flex Slider18. // The slider being synced must be initialized first19. $('#gallery-carousel').flexslider({

Simple Gallery System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_Gallery_System 34 / 35

Page 36: Basic Tutorials for ProcessWire

Privacy policy About ProcessWire Disclaimers

This page was last modified on 12 March 2013, at 20:21.

This page has been accessed 248 times.

20. animation: "slide",21. controlNav: false,22. animationLoop: false,23. slideshow: false,24. itemWidth: 149,25. itemMargin: 5,26. asNavFor: '#gallery-slider'27. });28. 29. $('#gallery-slider').flexslider({30. animation: "fade",31. animationSpeed: 1200,32. controlNav: false,33. animationLoop: false,34. slideshow: false,35. sync: "#gallery-carousel"36. });37. 38. });

The parameters used here are just f ollowing the options that are available onthe plugin sites - nothing special has been added.

Save the f ile and f ire up your website!

With any luck you now have a working gallery/album system, albeit with rathera lot of images on the album page! However, I leave it up to you to style thisand decide what you want to use when.

For instance, you could add a check box to the gallery template to be checkedif you want to use the slideshow. Then add an if (...) to decide whether the gridor the show is used on a page by page basis.

A lot is possible, with surprisingly lit t le work!

See Also

Basic Website TutorialSimple News System

Categories: Draf ts Long Tutorials

Simple Gallery System - ProcessWire 5/04/13

http://wiki.processwire.com/index.php/Simple_Gallery_System 35 / 35


Recommended