WordPress Responsive Theme Design - doc.lagout.org · Table of Contents WordPress Responsive Theme...

Preview:

Citation preview

WordPressResponsiveThemeDesign

TableofContents

WordPressResponsiveThemeDesign

Credits

AbouttheAuthor

AbouttheReviewers

www.PacktPub.com

Supportfiles,eBooks,discountoffers,andmore

Whysubscribe?

FreeaccessforPacktaccountholders

Preface

Whatthisbookcovers

Whatyouneedforthisbook

Whothisbookisfor

Conventions

Readerfeedback

Customersupport

Downloadingtheexamplecode

Downloadingthecolorimagesofthisbook

Errata

Piracy

Questions

1.ResponsiveWebDesignwithWordPress

TheconceptsofRWD

ControllingViewport

Scaling

Thescreendensity

Problemsandsolutionswiththescreendensity

TechniquesinRWD

Mediaqueries

Breakpoints

Fluidgrids

Frameworkspositives

Frameworksnegatives

Flexibleimagesandmedia

SettinguptheWordPressenvironment

InstallingandsettingupWordPress

Settinguptheunderscorestheme

InstallingtheWordPresstheme’sunittestdata

InstallingtheDeveloperplugin

Summary

2.UnderstandingtheWordPressThemeStructure

SettingWordPresspermalinks

WhatisaWordPresstheme?

Templatefiles

Thepagestructureoftemplatefiles

Themesubfolders

Summary

3.GettingStartedwithResponsiveLayout

Choosingtherighttoolforourproject

Howtosetupfunctions.php

Howtosetupstyles.css

Theemandremvalues

Addingmediaqueries

Summary

4.LearnHowtoCreatetheHeaderandNavigation

Makingourlayoutcentered

Dealingwiththeheader

Howtocreateamenuandmakeitresponsiveandaccessible

Menubasics

Stylingourmenu

Howtomakeourmenuaccessible

Howtomakeourmenuresponsive

Summary

5.CustomizingSinglePostTemplates

Analyzingsingleposttemplates

Analyzingthecontent-single.phpfile

Templateimprovements

Headerimprovements

Implementingchangestotheposttemplate

Stylingpost’smetadata

Contentsection

Tags

Postnavigation

Summary

6.ResponsiveWidgets,Footer,andComments

Widgets

Sidebars

Stylingsidebars

Editingthefooter

Workingwithcomments

Stylingcommentstitle

Stylingcomments

Commentsnavigation

Summary

7.WorkingwithImagesandVideos

Featuredimages

Settingupafeaturedimage

Resizingfeaturedimages

Imagecaptions

Imagegalleries

Makingthegalleryresponsive

Workingwithvideos

Summary

8.WorkingwithTemplateFiles

TheWordPresstemplatehierarchy

Excerpts

Featuredimages

Customizingthepagingnavigation

Stylingstickyposts

Modifyingarchive.php

Modifying404.php

Modifyingsearch.php

Summary

9.WorkingwithStaticPagesandAddingtheExtraFunctionalitywithPlugins

Homepage

Thehomepagetemplate

Stylesforthehometemplate

Sliderplugin

TheServicessection(listofservices)

Makingourhomepageresponsive

TheContactUspage

Summary

10.SubmittingYourThemetoWordPress.org

Polishingcodebeforesubmission

Applyingtheeditorstyles

ValidatingtheHTMLandCSScode

ValidatingtheJavaScriptcode

ValidatingthePHPcode

Debuggingthesetup

Multiplewp-config.phpsets

Addingthereadme.txtfile

Addingthescreenshot.pngfile

Runningathemecheckplugin

Summary

Index

WordPressResponsiveThemeDesign

WordPressResponsiveThemeDesignCopyright©2015PacktPublishing

Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.

Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthor,norPacktPublishing,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.

PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.

Firstpublished:June2015

Productionreference:1260615

PublishedbyPacktPublishingLtd.

LiveryPlace

35LiveryStreet

BirminghamB32PB,UK.

ISBN978-1-78528-845-6

www.packtpub.com

CreditsAuthor

DejanMarkovic

Reviewers

RoryAshford

JohnEckman

MattiaMigliorini

CommissioningEditor

DipikaGaonkar

AcquisitionEditors

NehaNagwekar

LarissaPinto

ContentDevelopmentEditor

RohitKumarSingh

TechnicalEditors

MrunalM.Chavan

RahulC.Shah

CopyEditors

SoniaMichelleCheema

GladsonMonteiro

VikrantPhadke

StutiSrivastava

NehaVyas

ProjectCoordinator

MaryAlex

Proofreaders

SimranBhogal

SafisEditing

MariaGould

Indexer

MonicaAjmeraMehta

ProductionCoordinator

NileshR.Mohite

CoverWork

NileshR.Mohite

AbouttheAuthorDejanMarkovicisthepresidentofNYTOGroup(http://www.nytogroup.com/),apremiumwebdevelopmentcompanywithofficesconvenientlylocatedinbothTorontoandNewYork.Heisanexperiencedwebdeveloperwiththeextensiveknowledgeofbothfrontendandbackendtechnologies(PHP,ASP.NET,JavaScript,ColdFusion,HTML5,CSS3,WordPress,Joomla,Drupal,tonamejustafew).

AsDejanstronglybelievesinreturningbacktothecommunity,hedevelopedandcontributedto2freeWordPressplugins:BufferMyPost(https://wordpress.org/plugins/buffer-my-post/)andTweetOldCustomPost(https://wordpress.org/plugins/tweet-old-custom-post/).HeisalsooneoftheorganizersofWPTorontomeetupgroupandtheWordCampToronto,anannualWordPressconference.

YoucanalwaysfindhimonvariousWordCamps(especiallytheoneswithindrivingdistancefromToronto)orexploringthenature,art&loveforfoodacrossCanada&US.Shouldyouhaveanyquestions,comments,concernsorjustwanttosayhello,youcanshoothimanemailat<dejan@dejanmarkovic.com>.Hewouldlovetohearyourthoughtsaboutthisbook.

DejanwasatechnicalreviewerofthebookLearningYeoman(http://www.amazon.com/Learning-Yeoman-Jonathan-Spratley/dp/1783981385).Thisishisfirsttimeasanauthor.

Iwouldliketothankmygirlfriend,lifepartner,andfuturewife,Tina,whoalwaysstoodbesidemethroughmybestandworsttimes.Thankyouforyourhelpandunderstanding,andyourtremendousandunconditionalsupport.Withoutyou,allofthiswouldhavebeenimpossible.Tina,youaremyshiningstar!

Iwouldalsoliketothankmymother,Spasenija,whoisstillmyinspirationandagreatexampleofasurvivorwhowentthroughalot.ThankyouMamaforeverything!

Thisbookwouldnothavebeenpossiblewithoutthesupportandloveofmybrother,Marko,mybeautifulsister-in-law,Nikolina,andthebestnephewsandnieceanyonecouldhave—Stefan,Luka,andAngelina.Iloveyouallverymuchandthankyouforyourunderstanding(especiallymynephewsandniece)asIhadtoworkonthisbookevenwhilestayingatyourhomeduringtheholidays.IamsosorrythatIdidn’thavemorefreetimetoplaywithyou.

Mysoon-to-bebrother-in-law,ToshaSerbian,hascreatedthelogoforthethemeTopcatthatweusedinthisbook.Tosha,thankyouforyourhelpandadvice.Itisgreatlyappreciated!

ManythankstoNehaNagwekar,NeetuMathew,RohitKumarSingh,LarissaPinto,andtherestofthePacktPublishingteam.

Ihaverecentlylosttwofamilymembersthatwereimportanttome,andthissectionisdedicatedtothem:

OurbelovedDragisa,

You’veleftusquietly,asyouhavelivedyourentirelife.Yourheart,whichtaughtushonesty,integrity,andloyalty,hasstopped.Weareleftherealone,withoutyou,withallthosememoriesoftrueappreciationandfriendship.Yourtimewascoloredwithmodesty,generosity,andself-sacrificingandstrenuouswork.Youwereourbackboneinthehardesttimesandwithyourgenerosityyouacceptedusasyourown.Wewillbeforevergrateful.Mayyouhaveeternalglory!

DearNoki,

Youwerethelightthatwasshiningonus.Yourpassiontohelpeverybodyandyourreliabilityaresomethingthatpeoplewillrememberyouby.

IwillneverforgetyouandIwillalwaysloveyouwithallmyheart.Yourwillbemybrotherforever!

AbouttheReviewersRoryAshfordisanEnglishwebdeveloper.HecurrentlymanagesthestudioatCodeBlueDigital.Inhissparetime,hehasbuilttheGridtacularresponsivegridsystem,WordpressBEMMenus,andotheropensourceprojects.

Iwouldliketothankmygirlfriend,Caroline,forherpatience(andhercoffee).Sheputupwithmewhenreviewingthisbookinthemidstofbuyingandmovingintoournewhouse.

JohnEckmanisthechiefexecutiveofficerof10up,adistributeddigitalagencythatfocusesondesigninganddeliveringgreatwebpublishingexperiencesonWordPress.

HereceivedaBAfromBostonUniversity,amaster’sdegreeininformationsystemsfromNortheasternUniversity,andaPhDfromtheUniversityofWashington,Seattle.Johnisanactivecontributortoanumberofopensourceprojectsandcommunities,andafounderandorganizerofWordCampBoston.Hepostsblogsatwww.openparenthesis.organdtweetsas@jeckman.

MattiaMigliorini,alsoknownasdeshack,isafreelancewebdesigneranddeveloperwholovesWordPress.Heisalwaysonthelookoutforamazingresponsivedesigns.HeisalsoanopensourceevangelistandamemberoftheUbuntucommunity.MattiacurrentlyworksbothasafreelancerandforVBItaliaSrl,anItaliane-commercecompany.

www.PacktPub.com

Supportfiles,eBooks,discountoffers,andmoreForsupportfilesanddownloadsrelatedtoyourbook,pleasevisitwww.PacktPub.com.

DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandasaprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusat<service@packtpub.com>formoredetails.

Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signupforarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooksandeBooks.

https://www2.packtpub.com/books/subscription/packtlib

DoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt’sonlinedigitalbooklibrary.Here,youcansearch,access,andreadPackt’sentirelibraryofbooks.

Whysubscribe?FullysearchableacrosseverybookpublishedbyPacktCopyandpaste,print,andbookmarkcontentOndemandandaccessibleviaawebbrowser

FreeaccessforPacktaccountholdersIfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccessPacktLibtodayandview9entirelyfreebooks.Simplyuseyourlogincredentialsforimmediateaccess.

PrefaceIfyouwanttoleaveyourmarkinthewonderfulworldofWordPress,thencontinuereading.ThisbookwillteachyouhowtodevelopandcustomizeyourveryownresponsivethemeinWordPress.Theaddedbenefitsforyouarethatyouwillgetalotofusefultipsandtricksthroughoutthebookintendedtomakeyourlifeeasier.WewillprovideyouwiththeessentialsinthedevelopmentoftheresponsivethemeinWordPressandtherestisuptoyouandyourimagination!

WhatthisbookcoversChapter1,ResponsiveWebDesignwithWordPress,introducesyoutotheconceptsandtechniquesofresponsivewebdesignandwalksyouthroughtheprocessofsettingupaWordPressenvironment.

Chapter2,UnderstandingtheWordPressThemeStructure,teachesyouabouttheWordPressthemearchitectureandthepurposeofthemostimportanttemplatefiles.

Chapter3,GettingStartedwithResponsiveLayout,startsyourdevelopmentjourneywhereyouwilllearnhowtochoosetherighttoolforyourproject(texteditororIDE),howtosetupfunctions.phpandstyles.css,setfontsandfont-icons,addmorenizr.jsandrespond.jsessentialscripts,andhowtoaddmediaqueries.

Chapter4,LearnHowtoCreatetheHeaderandNavigation,teachesyouaboutthemostimportantcomponentofanywebsite—navigation!

Chapter5,CustomizingSinglePostTemplates,focusesontheposttemplatesandtheircomponents:title,meta,andnavigation.Inthischapter,wearesettingupabasiclayoutthatwewilllaterexpandwiththeindextemplatesandstaticpages.

Chapter6,ResponsiveWidgets,Footer,andComments,introducesyoutothemagicworldofwidgets,footer,sidebar,andcommentswithalotofusefultipsandtricks.

Chapter7,WorkingwithImagesandVideos,startswithsomethingfunand,assomemightsay,themostinterestingcomponentsofanywebsite—imagesandvideos.Inthischapter,youwilllearnaboutfeaturedimages,imagecaptions,imagegalleries,andhowtoworkwithvideos.

Chapter8,WorkingwithTemplateFiles,focusesonthemostimportantfilesfortheWordPressthemes.Inthischapter,youwillunderstandtheWordPresstemplatehierarchy,understandthefunctionalityofarchivepagesandyouwillfindexcerptsonhowtocustomizethepagingnavigation,styleandstickypost,andalsohowtomodifyarchive.php,404.php,andsearch.php.

Chapter9,WorkingwithStaticPagesandAddingtheExtraFunctionalitywithPlugins,wrapsupthedevelopmentpartofourbook.Inthischapter,youwilllearnaboutstaticpages,sliders,shortcodes,howtomakeyourhomepageresponsive,andhowtomakethecontactuspage.

Chapter10,SubmittingYourThemetoWordPress.org,covershowtotestyourthemeandpolishyourcodebeforethesubmission,andhelpsyoulearnhowtosubmityourthemetotheWordPress.orgrepository.

WhatyouneedforthisbookThesoftwareapplicationsthatarerecommendedforthisprojectareXAMPP,WAMP,andMAMPpleasechooseonethatfitsyourneeds.Also,itwouldbebeneficialtohavetheWordPressinstalledlocallyoronthehostedenvironment.

WhothisbookisforThisbookisintendedforallofyouWordPressenthusiastswhowanttodevelopandcustomizeyourveryownWordPressresponsivetheme.SomeknowledgeofWordPress,PHP,MySQL,HTML,andCSSisexpectedfromyou.

ConventionsInthisbook,youwillfindanumberoftextstylesthatdistinguishbetweendifferentkindsofinformation.Herearesomeexamplesofthesestylesandanexplanationoftheirmeaning.

Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,pathnames,dummyURLs,userinput,andTwitterhandlesareshownasfollows:“Makesurethatthethemedirectoryisnamedtopcatandnottopcat_start.”

Ablockofcodeissetasfollows:

@mediaonlyscreenand(max-width:480px){

//mobilestyles

//upto480pxsize

}

Whenwewishtodrawyourattentiontoaparticularpartofacodeblock,therelevantlinesoritemsaresetinbold:

<divid="page"class="hfeedsitetopcat_page">

Newtermsandimportantwordsareshowninbold.Wordsthatyouseeonthescreen,forexample,inmenusordialogboxes,appearinthetextlikethis:“Thetaglinecanbefoundandsetinwp-adminbynavigatingtoSettings|General.”

NoteWarningsorimportantnotesappearinaboxlikethis.

TipTipsandtricksappearlikethis.

ReaderfeedbackFeedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbook—whatyoulikedordisliked.Readerfeedbackisimportantforusasithelpsusdeveloptitlesthatyouwillreallygetthemostoutof.

Tosendusgeneralfeedback,simplye-mail<feedback@packtpub.com>,andmentionthebook’stitleinthesubjectofyourmessage.

Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideatwww.packtpub.com/authors.

CustomersupportNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.

DownloadingtheexamplecodeYoucandownloadtheexamplecodefilesfromyouraccountathttp://www.packtpub.comforallthePacktPublishingbooksyouhavepurchased.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.

DownloadingthecolorimagesofthisbookWealsoprovideyouwithaPDFfilethathascolorimagesofthescreenshots/diagramsusedinthisbook.Thecolorimageswillhelpyoubetterunderstandthechangesintheoutput.Youcandownloadthisfilefromhttp://www.packtpub.com/sites/default/files/downloads/8456OS_ColorImages.pdf.

ErrataAlthoughwehavetakeneverycaretoensuretheaccuracyofourcontent,mistakesdohappen.Ifyoufindamistakeinoneofourbooks—maybeamistakeinthetextorthecode—wewouldbegratefulifyoucouldreportthistous.Bydoingso,youcansaveotherreadersfromfrustrationandhelpusimprovesubsequentversionsofthisbook.Ifyoufindanyerrata,pleasereportthembyvisitinghttp://www.packtpub.com/submit-errata,selectingyourbook,clickingontheErrataSubmissionFormlink,andenteringthedetailsofyourerrata.Onceyourerrataareverified,yoursubmissionwillbeacceptedandtheerratawillbeuploadedtoourwebsiteoraddedtoanylistofexistingerrataundertheErratasectionofthattitle.

Toviewthepreviouslysubmittederrata,gotohttps://www.packtpub.com/books/content/supportandenterthenameofthebookinthesearchfield.TherequiredinformationwillappearundertheErratasection.

PiracyPiracyofcopyrightedmaterialontheInternetisanongoingproblemacrossallmedia.AtPackt,wetaketheprotectionofourcopyrightandlicensesveryseriously.IfyoucomeacrossanyillegalcopiesofourworksinanyformontheInternet,pleaseprovideuswiththelocationaddressorwebsitenameimmediatelysothatwecanpursuearemedy.

Pleasecontactusat<copyright@packtpub.com>withalinktothesuspectedpiratedmaterial.

Weappreciateyourhelpinprotectingourauthorsandourabilitytobringyouvaluablecontent.

QuestionsIfyouhaveaproblemwithanyaspectofthisbook,youcancontactusat<questions@packtpub.com>,andwewilldoourbesttoaddresstheproblem.

Chapter1.ResponsiveWebDesignwithWordPressResponsivewebdesign(RWD)isawebdesignapproachaimedatcraftingsitestoprovideanoptimalviewingexperience—easyreadingandnavigationwithaminimumofresizing,panning,andscrolling—acrossawiderangeofdevices(frommobilephonestodesktopcomputermonitors).

Reference:http://en.wikipedia.org/wiki/Responsive_web_design.

Tosayitsimply,responsivewebdesign(RWD)meansthattheresponsivewebsiteshouldadapttothescreensizeofthedeviceitisbeingviewedon.

WhenIbeganmywebdevelopmentjourneyin2002,wedidn’thavetoconsiderasmanyfactorsaswedotoday.

Wejusthadtocreatethewebsitefora17-inchscreen(whichwasthestandardatthattime),andthatwasit.Yes,wealsohadtoconsider15,19,and21-inchmonitors,butsincethe17-inchscreenwasthestandard,thatwasthetargetscreensizeforus.Inpixels,thesesizeswereusually800or1024.Wealsohadtoconsiderafewernumberofbrowsers(InternetExplorer,Netscape,andOpera)andthestylingfortheprint,andthatwasit.

Sincethen,alotofthingshavechanged,andtoday,in2015,forawebsitedesign,wehavetoconsidermultiplefactors,suchas:

Alotofdifferentwebbrowsers(InternetExplorer,Firefox,Opera,Chrome,andSafari)Anumberofdifferentoperatingsystems(Windows(XP,7,and8),MacOSX,Linux,Unix,iOS,Android,andWindowsphones)Devicescreensizes(desktop,mobile,andtablet)Iscontentaccessibleandreadablewithscreenreaders?Howthecontentwilllooklikewhenit’sprinted

TipThroughoutthebook,wewillusetheRWDabbreviationforresponsivewebdesign,theIEabbreviationforInternetExplorer,andtheFFabbreviationforFirefoxbrowsers.

Today,creatingdifferentdesignforalltheselistedfactorsanddeviceswouldtakeyears.Thisiswherearesponsivewebdesigncomestotherescue.

Inthischapter,wewillcover:

TheconceptsofRWDTechniquesinRWDSettinguptheWordPressenvironment

TheconceptsofRWDIhavetopointoutthatthemobileenvironmentisbecomingmoreimportantfactorthanthedesktopenvironment.Mobilebrowsingisbecomingbiggerthanthedesktop-basedaccess,whichmakesthemobileenvironmentveryimportantfactortoconsiderwhendevelopingawebsite.Simplyput,themainpointofRWDisthatthelayoutchangesbasedonthesizeandcapabilitiesofthedeviceitsbeingviewedon.TheconceptsofRWD,thatwewilllearnnext,are:Viewport,scalingandscreendensity.

ControllingViewportOnthedesktop,Viewportisthescreensizeofthewindowinabrowser.Forexample,whenweresizethebrowserwindow,weareactuallychangingtheViewportsize.

Onmobiledevices,theViewportsizeisalsoindependentofthedevicescreensize.Forexample,Viewportis850pxformobileOperaand980pxformobileSafari,andthescreensizeforiPhoneis320px.

IfwecomparetheViewportsizeof980pxandthescreensizeofaniPhoneof320px,wecanseethatViewportisbiggerthanthescreensize.Thisisbecausemobilebrowsersfunctiondifferently.TheyfirstloadthepageintoViewport,andthentheyresizeittothedevice’sscreensize.Thisiswhyweareabletoseethewholepageonthemobiledevice.

IfthemobilebrowsershadViewportthesameasthescreensize(320px),wewouldbeabletoseeonlyapartofthepageonthemobiledevice.

Inthefollowingscreenshot,wecanseethetablewiththelistofViewportsizesforsomeiPhonemodels:

WecancontrolViewportwithCSS:

@viewport{width:device-width;}

Or,wecancontrolitwiththemetatag:

<metaname="viewport"content="width=device-width">

Intheprecedingcode,wearematchingtheViewportwidthwiththedevicewidth.

BecausetheViewportmetatagapproachismorewidelyadopted,asitwasfirstusedoniOSandthe@viewportapproachwasnotsupportedbysomebrowsersinthisbook,wewillusethemetatagapproach.

WearesettingtheViewportwidthinordertomatchourwebcontentwithourmobilecontent,aswewanttomakesurethatourwebcontentlooksgoodonamobiledeviceaswell.

Tip

WecansetViewportsinthecodeforeachdeviceseparately,forexample,320pxfortheiPhone.Thebetterapproachwillbetousecontent="width=device-width".

ScalingScalingisextremelyimportant,astheinitialscalecontrolsthezoomaspectofthecontentfortheinitiallookofthepage.Forexample,iftheinitialscaleissetto3,thecontentwillbeloadedinthesizeof3timesoftheViewportsize,whichmeans3timeszoom.Hereisthelookofthescreenshotforinitialscale=1andinitialscale=3:

Aswecanseefromtheprecedingscreenshots,ontheinitialscale3(threetimeszoom),thelogoimagetakesthebiggerpartofthescreen.

Itisimportanttonotethatthisisjusttheinitialscale,whichmeansthattheusercanzoominandzoomoutlater,iftheywantto.

Hereistheexampleofthecodewiththeinitialscale:

<metaname="viewport"content="width=device-width,initial-scale=1,

maximum-scale=1">

Inthisexample,wehaveusedthemaximum-scale=1option,whichmeansthattheuserwillnotbeabletousethezoomhere.Weshouldavoidusingthemaximum-scalepropertybecauseofaccessibilityissues.Ifweforbidzoomingonourpages,userswithvisualproblemswillnotbeabletoseethecontentproperly.

Thescreendensity

Asthescreentechnologyisgoingforwardeveryyearorevenfasterthanthat,wehavetoconsiderthescreendensityaspectaswell.Screendensityisthenumberofpixelsthatarecontainedwithinascreenarea.Thismeansthatifthescreendensityishigher,wecanhavemoredetails,inthiscase,pixelsinthesamearea.

Therearetwomeasurementsthatareusuallyusedforthis,dotsperinch(DPI)andpixelsperinch(PPI).DPImeanshowmanydropsaprintercanplaceinaninchofaspace.PPIisthenumberofpixelswecanhaveinoneinchofthescreen.IfwegobacktotheprecedingscreenshotwiththetablewhereweareshowingViewportsanddensitiesandcomparethevaluesofiPhone3GandiPhone4S,wewillseethatthescreensizestayedthesameat3.5inch,Viewportstayedthesameat320px,butthescreendensityhasdoubled,from163dpito326dpi,whichmeansthatthescreenresolutionalsohasdoubledfrom320*480to640*960.ThescreendensityisveryrelevanttoRWD,asnewerdeviceshavebiggerdensitiesandweshoulddoourbesttocoverasmanydensitiesaswecaninordertoprovideabetterexperienceforendusers.

Pixels’densitymattersmorethantheresolutionorscreensize,becausemorepixelsisequaltosharperdisplay.

Therearetopicsthatneedtobetakenintoconsideration,suchashardware,referencepixels,andthedevice-pixel-ratio,whichwewillnotcoverhere,asit’soutofthescopeofthisbook.

ProblemsandsolutionswiththescreendensityScalablevectorgraphicsandCSSgraphicswillscaletotheresolution.

ThisiswhywewilluseFontAwesomeiconsinourproject.FontAwesomeiconsareavailablefordownloadathttp://fortawesome.github.io/Font-Awesome/icons/.

FontIconsisafontthatismadeupofsymbols,icons,orpictograms(whateveryouprefertocallthem)thatyoucanuseinawebpagejustlikeafont.Theycanbeinstantlycustomized—size,drop,shadow,oranythingyouwantcanbedonewiththepowerofCSS.

Therealproblemtriggeredbythechangeinthescreendensityisimages,asforhigh-densityscreens,weshouldprovidehigherresolutionimages.

Thereareseveralwaysthroughwhichwecanapproachthisproblem:

Bytargetinghigh-densityscreens(providinghigh-resolutionimagestoallscreens)Byprovidinghigh-resolutionimageswhereappropriate(loadinghigh-resolutionimagesonlyondeviceswithhigh-resolutionscreens)Bynotusinghigh-resolutionimages

Asthisbookcoversonlytheessentials,wewillusethesecondapproach,providinghigh-resolutionimageswhereappropriate.

TechniquesinRWDRWDconsistsofthreecodingtechniques:

Mediaqueries(adaptcontenttospecificscreensizes)Fluidgrids(forflexiblelayouts)Flexibleimagesandmedia(thatrespondtochangestoscreensizes)

MoredetailedinformationaboutRWDtechniquesbyEthanMarcote,whoisthepersonwhocoinedthetermReponsiveWebDesign,isavailableathttp://alistapart.com/article/responsive-web-design.

MediaqueriesMediaqueriesareCSSmodules,orassomepeopleliketosay,justaconditionalstatement,whichtellsthebrowserstouseaspecifictypeofstyle,dependingonthesizeofthescreenandotherfactors,suchasprint(specificstylesforprint).Theyarehereforalongtimealready,asIwasusingdifferentstylesforprintin2002.

NoteIfyouwishtoknowmoreaboutmediaqueries,refertoW3CCandidateRecommendation8July2002athttp://www.w3.org/TR/2002/CR-css3-mediaqueries-20020708/.

Hereisanexampleofmediaquerydeclaration:

@mediaonlyscreenand(min-width:500px){

font-family:sans-serif;

}

Let’sexplaintheprecedingcode.

The“@media”codemeansthatitisamediatypedeclaration.

The“screenand”partofthequeryisanexpressionorcondition(inthiscase,itmeansonlyscreenandnoprint).

Thefollowingconditionalstatementmeansthateverythingabove500pxwillhavethefontfamilyofsansserif:

(min-width:500px){

font-family:sans-serif;

}

Hereisanotherexampleofamediaquerydeclaration:

@mediaonlyscreenand(min-width:500px),screenand(orientation:

portrait){

font-family:sans-serif;

}

Inthiscase,ifwehavetwostatementsandifoneofthestatementsistrue,theentiredeclarationisapplied(eithereverythingabove500pxortheportraitorientationwillbeappliedtothescreen)

NoteTheonlykeywordhidesthestylesfromolderbrowsers.

Assomeolderbrowsersdon’tsupportmediaqueries,wewillusearespond.jsscript,whichwill“patch”supportforthem.

Polyfill(orpolyfiller)iscodethatprovidesfeaturesthatarenotbuiltorsupportedbysomewebbrowsers.Forexample,anumberofHTML5featuresarenotsupportedbyolderversionsofIE(olderthan8or9),butthesefeaturescanbeusedifpolyfillisinstalledonthewebpage.Thismeansthatifthedeveloperwantstousethesefeatures,he/shecanjustincludethatpolyfilllibraryandthesefeatureswillworkinolderbrowsers.

BreakpointsBreakpointisamomentwhenlayoutswitches,fromonelayouttoanother,whensomeconditionisfulfilled,forexample,thescreenhasbeenresized.Almostallresponsivedesignscoverthechangesofthescreenbetweenthedesktop,tablets,andsmartphones.

Hereisanexamplewithcommentsinside:

@mediaonlyscreenand(max-width:480px){

//mobilestyles

//upto480pxsize

}

Mediaqueryintheprecedingcodewillonlybeusedifthewidthofthescreenis480pxorless.

@mediaonlyscreenand(min-width:481px)and(max-width:768px){

//tabletstyles

//between481and768px

}

Mediaqueryintheprecedingcodewillonlybeusedthewidthofthescreenisbetweenthe481pxand768px.

@mediaonlyscreenand(min-width:769px){

//desktopstyles

//from769pxandup

}

Mediaqueryintheprecedingcodewillonlybeusedwhenthewidthofthescreenis769pxandmore.

NoteTheminimumwidthvalueindesktopstylesis1pixeloverthemaximumwidthvalueintabletstyles,andthesamedifferenceistherebetweenvaluesfromtabletandmobilestyles.Wearedoingthisinordertoavoidoverlapping,asthatcouldcauseproblemwithourstyles.

Thereisalsoanapproachtosetthemaximumwidthandminimumwidthwithemvalues.Settingemofthescreenformaximumwillmeanthatthewidthofthescreenissetrelativetothedevice’sfontsize.Ifthefontsizeforthedeviceis16px(whichistheusualsize),themaximumwidthformobilestyleswouldbe480/16=30.Whydoweuseemvalues?Withpixelsizes,everythingisfixed;forexample,h1is19px(or1.5emofthedefaultsizeof16px),andthat’sit.Withemsizes,everythingisrelative,soifwechangethedefaultvalueinthebrowserfrom,forexample,16pxto18px,everythingrelativetothatwillchange.

Therefore,allh1valueswillchangefrom19pxto22pxandmakeourlayout“zoomable”.Hereistheexamplewithsizeschangedtoem:

@mediaonlyscreenand(max-width:30em){

//mobilestyles

//upto480pxsize

}

@mediaonlyscreenand(min-width:30em)and(max-width:48em){

//tabletstyles

//between481and768px

}

@mediaonlyscreenand(min-width:48em){

//desktopstyles

//from769pxandup

}

FluidgridsThemajorpointinRWDisthatthecontentshouldadapttoanyscreenit’sviewedon.Oneofthebestsolutionstodothisistousefluidlayoutswhereourcontentcanberesizedoneachbreakpoint.

Influidgrids,wedefineamaximumlayoutsizeforthedesign.Thegridisdividedintoaspecificnumberofcolumnstokeepthelayoutcleanandeasytohandle.Thenwedesigneachelementwithproportionalwidthsandheightsinsteadofpixelbaseddimensions.Sowheneverthedeviceorscreensizeischanged,elementswilladjusttheirwidthsandheightsbythespecifiedproportionstoitsparentcontainer.

Reference:http://www.1stwebdesigner.com/tutorials/fluid-grids-in-responsive-design/.

Tomakethegridflexible(orelastic),wecanusethe%points,orwecanusetheemvalues,whicheversuitsusbetter.Wecanmakeourownfluidgrids,orwecanusegridframeworks.Astherearesomanyframeworksavailable,Iwouldrecommendthatyouusetheexistingframeworkratherthanbuildingyourown.

Gridframeworkscoulduseasinglegridthatcoversvariousscreensizes,orwecanhavemultiplegridsforeachofthebreakpointsorscreensizecategories,suchasmobiles,tablets,anddesktops.

FrameworkspositivesThekeypositivefeaturesofframeworksare:

Fasterprototyping:Ourclientscanseeandapproveourprototypesfaster.Fasterdevelopment:Thecostbornebytheclientisreduced.Wecannowcompletemoreprojectswithinthesametimeperiod.

FrameworksnegativesThekeynegativefeaturesofframeworksare:

IttakessometimetolearntheframeworkrulesTheyareusuallyclass-basedwithnon-semanticclassnames,whichcanclutterupourcodeTheyaddextracontainerelements,whichmakesourHTMLcodebiggerTheyarelargeinsizeandthatincreasesthepageloadingtime

SomeofthenotableframeworksareTwitter’sBootstrap,Foundation,andSemanticUI.IpreferTwitter’sBootstrap,asitreallyhelpsmespeeduptheprocessanditisthemostusedframeworkcurrently.

FlexibleimagesandmediaLastbutnottheleastimportant,areimagesandmedia(videos).Theproblemwiththemisthattheyareelementsthatcomewithfixedsizes.Thereareseveralapproachestofixthis:

ReplacingdimensionswithpercentagevaluesUsingmaximumwidthsUsingbackgroundimagesonlyforsomecases,asthesearenotgoodforaccessibilityUsingsomelibraries,suchasScottJehl’spicturefillTakingoutthewidthandheightparametersfromtheimagetaganddealingwithdimensionsinCSS

WewilltacklethisquestinmoredetailinChapter7,WorkingwithImagesandVideos.

SettinguptheWordPressenvironmentInordertoachievearesponsivedesignforaWordPresssite,youneedaWordPressthemethatemploysthebasictechniquesofRWD.

Inthissection,wewillcover:

InstallingandsettingupWordPressSettingupunderscores(thestartertheme)andexplainingwhyweuseitInstallingtheWordPresstheme’sunittestdataInstallingtheDeveloperplugin

InstallingandsettingupWordPressBeforewebeginwithanycoding,weneedtomakesurethatwesetupourdevelopmentenvironment.Therearenumerouswayswecandoit,butmypreferenceistohave:

LocalinstallationontheharddriveAutomaticsyncingtoourserver(thisstepisoptional)

IperformautosyncingtomyserverbecausemylocalenvironmentisWindowsandmyserverenvironmentisLinux(CentOS).Throughmanyyearsofdevelopment,I’veseenmanytimesthatlocalandserverenvironmentdifferencescancausealotofheadache,soItrytotestthecodeonbothwhileIamworking.

Inordertomakeyourlifeeasier,IwouldrecommendthatyoudownloadthePHPdevelopmentenvironments.ForWindows,therearethreePHPdevelopmentenvironmentsthatIhighlyrecommend:

XAMPP(www.apachefriends.org/index.html)WAMP(www.wampserver.com/en/)Bitnami(www.bitnami.com/stack/wordpress)

ThesepackageswillinstallandconfigureApache,Mysql,andPHPautomaticallyforyou.OnlyBitnamiwillinstallWordPressforyouaswell.Allofthemareprettygoodandthechoicejustdependsonyourpreference.IuseXAMPPasIamusedtoit.

ForMacOSX,Irecommend:

MAMP(www.mamp.info/en/)XAMPP(www.apachefriends.org/index.html)Bitnami(www.bitnami.com/stack/wordpress)

IwasusingMAMPonMacOSXandhadnoissues.MAMPProisevenbetter,asitprovidesmoreoptionstomakeourlifeeasier,anditiswellworththeinvestment.Whenthesepackagesareinstalled,WordPressshouldbedownloadedfromhttp:/www.wordpress.org/download/.Afteritisdownloaded,WordPressshouldbeunpacked(unzipped)andplacedinwebserver’spublicdirectorywiththeprojectname;inmycase,onWindowswithXAMPPinstalled,thisisC:\xampp\htdocs\topcat.

NoteOurproject,whichwewilluseinthisbookasanexample,iscalledtopcat.HereisagreatguideinhowtoinstallWordPresslocallyathttp://codex.wordpress.org/Installing_WordPress.

AfterWordPressisinstalled,our_sorunderscoresstarterthemeshouldbedownloadedandinstalled.

SettinguptheunderscoresthemeUnderscores(_s)isthestarterthemeforWordPress.IthasbeencreatedbythepeoplefromAutomattic(thecompanythatstandsbehindWordPress)andnumerouscontributors.Whyisthisthemesogood?ItisgoodbecauseitfollowsalltherulesfromWordPress.org,anditreallymakesourliveseasier,aswedon’thavetostartdevelopingthethemefromscratch.Thereareanumberofstarterthemesthatcanbeusedfortheprojects,andIhaveclosedthisoneasit’sreallypopularandhasalotoffeaturesimplemented(pagetemplates,customizer,layouts,andlanguages)inordertomakeourliveseasier.

Ifyouareaninexperienceddeveloperandyouwanttofollowmefromnowon,IsuggestthatyougoanddownloadthesameversionofthethemeastheoneIdownloadedfrom:https://github.com/dejanmarkovic/topcat_start.Makesurethatthethemedirectoryisnamedtopcatandnottopcat_start.Ifyouwanttostartwiththefinishedcode,thenpleasedownloadthisversionfrom:https://github.com/dejanmarkovic/topcat.Ontheotherhand,ifyouprefertostartwiththelatest_sversion(atyourownrisk,asthecodemightchangealotfurtherinthisbook),youcandownloaditfromhttps://github.com/Automattic/_s/,orfromherehttp://underscores.me/.

TipThegoodthingaboutdownloadingthethemefromtheunderscoreswebsiteratherthanfromGitHubisthatyoucansetathemenamethere.

Nowlet’sgetstarted:

1. Putthethemeinthethemesdirectory.ThethemelocationshouldlooklikethisC:\xampp\htdocs\topcat\wp-content\themes\topcat(onWindows).

2. ActivatethethemebyclickingontheActivatebuttoninwp-admin.Yourscreenshouldlooklikethis:

Don’tworry,wewillsoonbechangingthisflat-lookingthemeintoanice-lookingresponsivewebdesign.

3. Wheninstalled,thetheme’spreviewshouldlooklikethis:

InstallingtheWordPresstheme’sunittestdataUnittestdatafillstheWordPressdatabasewithsampleposts,pagesandcommentsspanningacrossdifferentposttypes,imagesizes,tags,andcategories.Itmakesourliveseasierwhiledevelopingthetheme,aswedon’thavetoaddallthatcontentourselvesandwearesurewhenwetestthecodeofourthemewithallthatcontentloadedthatwewillbeabletoseeifsomethingbreaks.

WecantestthefeaturesofourthemebyusingtheunittestdatathatisalsousedbytheWordPress.orgthemeteamwhenwesubmitourtheme.Itcanbedownloadedfrom:https://wpcom-themes.svn.automattic.com/demo/theme-unit-test-data.xml.

NoteMoreinformationaboutthemetestingisavailableathttp://codex.wordpress.org/Theme_Unit_Testandathttp://codex.wordpress.org/Theme_Development#Theme_Testing_Process.Ifyouhaveyourowncontentthatyouwanttouse,youcanuseit.IcertainlyrecommendthatyouusetheWordPresstheme’sunittestdataasitcoversallthecasesforthemes,andtheWordPress.orgteamusesitwhentheytestyourthemeforapproval.

InstallingtheDeveloperpluginInthefinalstepinthischapter,wehavetoinstalltheDeveloperplugin.Wecaninstallitbygoingtopluginsectionofwp-adminandthenbysearchingforthatpluginathttp://localhost/topcat/wp-admin/plugin-install.php.Hereisthescreenshotofhowtheexactresultshouldlooklike:

NotethattheauthorofthepluginshouldbeAutomattic.Or,wecandownloadthe.zipfilefromhttps://wordpress.org/plugins/developer.

Now,performthefollowingsteps:

1. Duringtheinstallation,youwillbepromptedtochoosebetweenthreeoptions:

Thepluginforaself-hostedWordPressinstallationThethemefortheself-hostedWordPressinstallationThethemefortheWordPress.comVIPwebsite

2. Pleasechoosethesecondoption.3. BecausetheDeveloperpluginactuallyconsistsofmanysmallerplugins,weshould

installtheonesthatweneed.4. Iamgoingtochoosethefollowing:

DebugBar(ItprovidesadebugmenuintheWordPressadminbar.Inthedebugmenu,youcanviewquery,cache,andotherrelevantdebugginginformation).DebugBarConsole(ItaddsaPHP/MySQLconsoletothedebugbar).DebugBarCron(ItaddsanewpaneltoDebugBarthatdisplaysinformationaboutscheduledeventswithinWordPress).DebugBarExtender(Itextendsthedebugbarwithfeaturessuchasvariablelookup,profiler,andsoon)Monsterwidget(Itprovidesaquickandeasymethodtoaddallcorewidgetstoasidebarfortestingpurposes.Thismeansthatitwilladdallcorewidgetsatoneplacesothatwecaneasilyseewhethersomethinghadbrokethelayout.)Regeneratethumbnails(EachWordPressthemehasitsownimage/thumbnailsettings.So,ifweswitchfromonethemetoanother,weshouldregeneratethe

thumbnailsinordertomakesurethatthumbnailspropertiesmatchthesettingsinthetheme.ThemeCheck(Itteststhethemeagainstthelateststandardsandpracticesandprovidesthefeedback.)WearegoingtouseisinChapter10,SubmittingYourThemetoWordPress.org,beforewesubmitourthemetoWordPress.org.

ThisismychoiceofpluginswithinthedeveloperpackthatIuse,andyouarefreetouseothersifyouwant.Ifyouwanttochangeanyofthesettingsthatyouhavealreadychosen,youcangotoTools|Developerinwp-adminandchangethemthere.

SummaryInthischapter,wefirstcoveredRWDconceptssuchasViewportscalingandthescreendensity.Secondly,wecoveredtheRWDtechniques:mediaqueries,fluidgrids,andflexiblemedia.Finally,wespentsometimesettingupourWordPressenvironmentbyinstallingWordPress,underscorestheme,WordPresstheme’sunittestdata,andtheDeveloperplugin.

Inthenextchapter,wewillcovertheWordPressthemearchitectureandthepurposeofthemostimportanttemplatefiles.

Chapter2.UnderstandingtheWordPressThemeStructureAswehavealreadyinstalledandsetupWordPressandourstarterunderscorestheme,wearenowcontinuingourjourneyand,inthischapter,wewilllearnabouttheWordPressthemearchitectureandthepurposeofthemostimportanttemplatefiles.

Withoutfurtherado,inthischapterwewillcover:

TheWordPresspermalinksfunctionalityWordPressthemestructureWordPresstemplatefiles

SettingWordPresspermalinksWhenuserscometoourpage,forexample,http://localhost/topcat/about,theyusuallyseethepermalinkthatissetasapostname,ortheyjustseethepostID.Italldependsonthecurrentsettingsinwp-admin.ThepermalinkssectioncanbereachedbygoingtoSettings|Permalinks.DefaultsettingsarealwayssetonapostID,butrecommendedsettingsshouldbesettothepostnamebecauseofSearchEngineOptimization(SEO)purposes.Theaboutpostnamemakesmoresensethanp=123inhttp://localhost/topcat/p=123.

NoteWithSEO,weareoptimizingthewebsitepropertiesinordertomakeourwebsitemoreappealingtosearchengines.Withpermalinks,wearemakingourURLreadableandsearchablebyhumans.Itiseasiertofindthetermdejanmarkovicwordpressifwehaveapageforit,asinthedejanmarkovic.com/wordpressexample,ratherthandejanmarkovic.com/page=?123.

Hereisanexampleofthepermalinkssettingsinwp-admin:

NotePleasenotethatpermalinksintheprecedingscreenshotaresettoPostname.

Thenagain,whentheusercomestoourpage,http://localhost/topcat/about,andtheaboutpermalinkisrecognizedinthebackendasthepostID(asthat’showthepostsarestoredinthedatabase),thedatabasewillfigureoutwhetherthepageisoftheposttype,page,orsomethingelse.

Refertothefollowingfigureforanexplanationofthestepsnumberedfromtoptobottom:

Inthiscase,becausetheaboutpageisofthepagetype,page.phpisloaded.

NoteNotethatWordPresssavesposts,pages,categories,andmenuitemswiththeircustomIDsinthedatabasesystem,sothedatabasecancheckthetypeoftheitembyID.

WhatisaWordPresstheme?WordPressthemeisagroupoffiles(templatefiles)thatareworkingtogethertodisplaythecontenttoendusers.Themesareextensions,likeplugins,totheWordPresscorefileandtheirpurposeistocustomizethefront-endofthewebsite.Theyalsoallowuserswhohaveaccesstothedashboard(usuallyadmins)tocustomizethelookofthewebsite.

NoteNotethatWordPressadminthemeshavebeengainingpopularityin2015andthesethemesareusedtochangethelookoftheWordPressdashboard(admin).

TemplatefilesThestyle.cssfileisaCSSfilewherethemeinformationisstored.Thereareanumberofvariablesinthisfile,aswecanseeinthefollowingscreenshot:

Let’sexamineeachofthesevariables.Theyareasfollows:

ThemeName:Thisisthenameofthetheme.ThemeURI:Thisisthelocationofthetheme.Iamusingthelocationonmyhttp://dejanmarkovic.com/websiteuntilmythemegetsapprovedbythethemeteamatWordPress.org.ThenIwillmovethethemetoalocationontheWordPress.orgwebsite.Author:Thisisthenameoftheauthorofthetheme(inthiscase,yourstruly).AuthorURI:Thisistheauthor’swebsiteURL.Description:Thisistheplacewhereweshoulddescribethethemewithasmanydetailsaswecan,becausethisvaluewillattractourusers/customers.Aswehavejuststarted,Ihaveprovidedonlythebasics.Ihighlyrecommendthatyouupdatethisvaluewhenyoucompleteyourjourneyinordertomakeyourthememoreinterestingandunique.Version:Thisisourcurrentversionofthistheme.Whenourthemegetspublished,weshouldchangetheversionnumbereachtimewemakeasubstantialchange.

NoteNotethatweshouldnotchangetheversionnumberforeverysimplechangebutforeachcommit.

Forexample,ifwefixthebug,thatfixwillcontainmultiplechanges,butwewillcommitthecodetoWordPress.orgonlyonce.JustbeforecommittingthecodetoWordPress.org,weshouldchangetheversionvalue.

License:Weshouldstatethelicenseweareusingforthistheme.AswearegoingtosubmitourthemetoWordPress.org,itshouldhavethesamelicenseasWordPress:GNUGeneralPublicLicensev2.LicenseURI:ThisisthelocationoftheLICENSEfile.TextDomain:Thisisusedforlocalization(makingyourthemetranslationready).Wewillmakeourthemetranslation-ready,andwewillcoverthatinmoredetaillaterin

thisbook.Tags:Thisvariableiswhereyoucanchoosethetagsthatdescribeyourthemefeatures/options.Forthisoption,weshouldonlyusethetagsthatareallowedonWordPress.org.Pleaseusethehttps://wordpress.org/themes/tag-filterpageasareferenceandclickontheFeatureFilteroptioninordertoseethetags.Ifyourthemehasthesamefeaturesasmine,pleasefeelfreetousethetagsthatI’veused.

Whenwecompletethesettingsofourvariables,wecanseetheresultsbygoingtoAppearance|ThemesandthenclickingontheActive:TopCatoptiononTopCat’sareainwp-admin,asyoucanseeinthefollowingscreenshot:

Asoftwarelicenseisalegalinstrument(usuallybywayofcontractlaw,withorwithoutprintedmaterial)governingtheuseorredistributionofsoftware.UndertheUnitedStatescopyrightlaw,allsoftwareiscopyrightprotected,exceptmaterialinthepublicdomain.Atypicalsoftwarelicensegrantsanenduserpermissiontouseoneormorecopiesofsoftwareinwayswheresuchausewouldotherwisepotentiallyconstitutecopyrightinfringementofthesoftwareowner’sexclusiverightsundercopyrightlaw.

-http://en.wikipedia.org/wiki/Software_license

Then,wecanclickontheCustomizebuttoninordertobeforwardedtothethemedetailspage,asshowninthefollowingscreenshot:

Aswecanseeintheprecedingscreenshot,thename,author,description,andtagsaredisplayed.

NotePleasenotethatwehaveanimageontheleft-handsidethatlookslikethechessboard.Thisisactuallythedefaultimage’sscreenshot.pngfileprovidedwiththetheme.Wewillchangethisimagelaterontodisplayourthemelayout.

ThepagestructureoftemplatefilesHereisascreenshotshowingthefilesinourtemplatedirectory:

WordPresspagesaremadefromthefollowingsections,whichareactuallyallseparatefiles:

header.php

Contentfilessuchasindex.php,page.php,single.php,andsoonfooter.php

sidebar.php(optional)

Theheader.phppagecontainsalltheelementsthatareneededatthetopofeachHTMLpage,includingdoctype,openingHTML,meta,titletags,bloginfo,stylesheets,andwebsitenavigation.

Thecontentfilesarescaffoldingfiles,whichhaveascaffoldingcodethatcallstheheader,footer,andotherfilesbasedonthecontenttype.

Thefooter.phpfilecontainstheinformationthatgoesatthebottomofyourpage(closingtagsand,insomecases,callstofootersidebars/widgets).

Thesidebar.phpfileiswheresidebarinformationisfound(thisisanoptionalfile,as

somethemesmaynothavesidebars).

Theindex.phpfileisoneofthemostimportantscaffoldingtemplatefiles.Itspurposeistoshowtheblog’sindexpageoranyotherindexpage.Itisalsousedifthesystemcan’tlocatethedesignatedtemplatepage,suchaspage.phpandsingle.php,thatwearegoingtocoverfurther.

Incaseswherewehaveablog,wejustgototherootoftheblog(theindexpage)anditwillloadcontent.phpintheloopforeachblogpost,liketheoneshowninthefollowingscreenshot:

Asyoucanseeintheprecedingscreenshot,wehavefunctioncallstoget_header(),get_footer(),andget_sidebar().Withthesecalls,wearecallingtheheader.php,footer.php,andsidebar.phpfiles.Wecanalsocheckwhethertherearepostsinthedatabasewiththeif(have_posts())code.Ifthereareposts,thenitwillcallthecontenttemplate,thecontent.phppage,withtheget_template_part('content',get_post_format());code.Iftherearenopostsinthedatabase,thenitcallsthecontent-none.phptemplate.

Thereisanotherinterestingcallinourcodeandthatistopcat_paging_nav().Thisisthe

callforpagination.Ithasourthemename,topcat,init.Thisprefixwasaddedonthehttp://underscores.me/pagewhenIchosethethemename.Theprefix(topcat)wasaddedtoallthemefunctionsanditissupposedtomakethemuniqueandavoidcausingconflicts.HereisanexcerptthatexplainsthisfromtheWordPresscodex:

AllthefunctionsinyourPluginneedtohaveuniquenamesthataredifferentfromfunctionsintheWordPresscore,otherPlugins,andthemes.Forthatreason,itisagoodideatouseauniquefunctionnameprefixonallofyourPlugin’sfunctions.AfarsuperiorpossibilityistodefineyourPluginfunctionsinsideaclass(whichalsoneedstohaveauniquename).

-http://nacin.com/2010/05/11/in-wordpress-prefix-everything/

NoteMoreinformationonthisprovidedbyAndrewNacin,whoisoneoftheleaddevelopersforWordPress,isavailableathttp://nacin.com/2010/05/11/in-wordpress-prefix-everything/.

Ifyouwanttopublishyourtheme,thenyoushouldmakesuretochangethetopcatprefixtosomethingelsethatisunique.

Thecontentfilesaredescribedasfollows:

page.php:Thisisascaffoldingfileforpagesandithassimilarcodetoindex.php.Ithasthe_content();callthatcallscontent-page.php.single.php:Thisisthescaffoldingfilethatwillbeusedifouraboutpermalink(mentionedpreviously)linkstoapostinsteadofthepage,anditwillloadthecontentfromcontent-single.php.search.php:Thisisascaffoldingfilewheresearchresultsareshown.archive.php:Thisisascaffoldingfilethatdisplaysarchivedpages.comments.php:Thisisascaffoldingfilethatdisplayscomments.404.php:Thisisascaffoldingtemplatefor404pages.rtl.css:Intherootfolder,wealsohavertl.css,whichistheCSSfileforright-to-leftlanguages(languagesthatarewrittenfromrighttoleft).LICENSE:Thisfileisobviouslyusedforlicensingpurposes.AswearegoingtopublishthisthemeonWordPress.org,thelicenseshouldbeGPLv2(thesameastheWordPresslicense).README.md:ThisfileisusedforprojectdescriptionsonGitHub.functions.php:ThisisafilewhereweareabletoaddourownfunctionalitytoathemethatisnotapartoftheWordPresscore.Inordertodothis,wecanalsocalltheWordPresscorefunctions.

Asthefileistoobigforthisbook,Ihaveextractedthecodeintosmallexcerpts,whichwewillanalyzetogether:

Online11oftheprecedingscreenshot,wehaveaconditionalstatementthatmeans:‘ifthecontentwidthisnotset,wearesettingitto640px’.Thecodeforthisisasfollows:

if(!isset($content_width)){

$content_width=640;/*pixels*/

}

Weneedtohavethesetupfunctionforourthemeand,online15ofthefollowingscreenshot,wecheckwhetherthetopcat_setupfunctionisalreadydeclaredsomewhereelse:

Online21ofthefollowingscreenshot,wearesettingupthetopcat_setupfunction,whichsetsthetheme’sdefaultsandaddssupportforsomefeaturesthatwewillcoverindetaillaterinthischapter.

Online31ofthenextscreenshot,weareaddingsupportforlocalization(supportforourthemetobetranslatedintootherlanguages):

Online34ofthefollowingscreenshot,weareaddinglinkstoRSSfeedsfromcommentsandpoststotheheader:

Online45,weareregisteringourtheme’sprimarymenu,asshowninthefollowingfigure:

NoteNotethataddinglinkstoRSSfeedsfromcommentsandpoststotheheaderisgoodforSEOpurposesasweshouldinsertasmuchinformationaswecanforsearchenginessuchasGoogletopickthatinformation.Ifmoreinformationisprovided,oursitewillbeeasiertofind.

TipAlsonotethatWordPressthemescanhavemultiplemenus.

Online45ofthefollowingscreenshot,weareaddingHTML5supportforsearchforms,comments,andsoon.ThismeansthatHTML5tagswillreplacetheoldHTMLtagsfortheseelements.

Inthefollowingcodescreenshot,supportforpostformatssuchasvideo,image,andothersisenabled:

TipAPostFormatisapieceofmetainformationthatcanbeusedbyathemetocustomizeitspresentationofapost.ThePostFormatsfeatureprovidesastandardizedlistofformatsthatareavailabletoallthemesthatsupportthefeature.

-https://codex.wordpress.org/Post_Formats

Online65,weareaddingthesupportforthecustombackgroundinwp-admin.ThisoptioncanbereachedbygoingtoAppearance|Background,asshowninthefollowing

screenshot:

Online78ofthefollowingscreenshot,wearesettingupourfirstsidebar:

NotePleasenotethatWordPressthemescanhavemultiplesidebars.

Wewilladdmoresidebarslaterinthisbook.

Online94ofthefollowingscreenshot,weareaddingthecallforourdefaultstylesstyle.cssandscriptssuchasnavigation:

IfwewanttoaddsomecustomCSSandJavaScript,weshouldusethewp_enque_style()andwp_enque_script()functions,respectively,asshownnext:

wp_enqueue_style('topcat-style',get_stylesheet_uri());

wp_enqueue_script('topcat-navigation',get_template_directory_uri().

'/js/navigation.js',array(),'20120206',true);

wp_enqueue_script('topcat-skip-link-focus-fix',

get_template_directory_uri().'/js/skip-link-focus-fix.js',array(),

'20130115',true);

if(is_singular()&&comments_open()&&get_option('thread_comments'))

{

wp_enqueue_script('comment-reply');

}

Inthenextsection,weareperformingthefollowingsteps:

1. Addingsupporttothecustomheader(thiscodeiscommentedoutasthefunctionalityisoptional).

2. Addingtemplatetagfunctionality.3. Addingtheextras.phpfileforcustomfunctionsthatarenotassociatedwith

templatefiles.4. Makingadditionstothethemecustomizer.5. AddingsupportfortheJetpackplugin.

Thesestepsareshowninthefollowingscreenshot:

ThemesubfoldersInthispart,wewillcoverthesubfoldersofthe_stheme.Let’sgofromthebottomtothetop.

Inthelayoutsfolder,wehavetwoCSSfiles,content-sidebar.cssandsidebar-content.css,whicharelayouttemplates.Inthisbook,wewillusecontent-sidebar.css,asoursidebarwillbeontheright-handsideonsomepages.

Thelanguagesfolderisusedforlocalization(language)filesthathavethe.potextension.

Inthejsfolder,weshouldstoreanyofourJavaScriptfiles.Wealreadyhavesomefilesthataretherebydefault:

navigation.js:Thisfileisusedfornavigation.customizer.js:Thisfileisusedforthemecustomizerfunctionality.

NoteSinceVersion3.4,WordPresshasaddedsupportforthethemecustomizer.Thisoptionallowstheusertochangethetheme’slooksandsettingsbyjustgoingtothecustomizesectionoftheirthemebynavigatingtoAppearance|Customize.

skip-link-focus-fix.js:UsersofOperaandWebKitbrowsersthatusethekeyboardinsteadofamousewhenclickonaskiplinkthebrowsersdon’tproperlymovethefocustoitstarget.ThisfilefixesthefocusproblemintheOperaandWebKitbrowserswhenusingskiplinks.skiplinks:Thisisafunctionalitythatweimplementonapageifthepagehasmultiplesections.Whentheuserclicksonthatlink,thepagejumpstothedesignatedsection.incfolder:Thisistheplacewhereweshouldputthefilesthatextendthefunctionalityofthetheme.Wealreadyhavesomefilesthere,asfollows:

custom-header.php:Thisisthefilecontainingourcustomheaderfunctionality(thisfileisoptional)customizer.php:Thiscontainsextensionsforthethemecustomizermentionedpreviouslyextras.php:Thiscontainscustomfunctionsnotassociatedwithtemplatefilesjetpack.php:ThisisthefilewheresupportfortheJetpackpluginisadded

NoteWhatisJetpack?JetpackisagroupoffeaturesandpluginsthatareusedonWordPress.comandcanbeinstalledonself-hostedwebsites.Thegoodthingaboutitisthatallthesefeaturesweretestedonhigh-trafficwebsitessuchasWordPress.comandtheyareoptimizedforbestperformance.Becauseofallthat,theyarelessbuggytoo.Usually,ifsomeonehasaproblem/conflictwithJetpackonhis/herwebsite,it’sbecauseothercustompluginsorathemehaveconflictswithitandnotbecauseJetpackitselfisaproblem.IfweneedafeatureforourwebsitethatiscoveredwithJetpack,Iwouldsuggestthatyouuse

JetpackratherthanacustompluginthathasnotbeentestedasJetpack.Ontheotherhand,Iwouldstronglyrecommendthatyouuseonlyfeaturesthatyouneedratherthanenablingallfeatures,asthatwillreallyslowdownyourwebsite.

Templatetags,whicharecontainedinthetemplate-tags.phpfile,areactuallyWordPressfunctionsthatwecancallinordertohavesomefunctionality.Forexample,topcat_posted_on()willdisplaythetimeandauthorinformationforthepost.Thetopcat_post_nav()functionwilldisplaytheprevious/nextfunctionality.

SummaryAtthebeginningofthischapter,wecoveredthepermalinksfunctionalityofWordPress.Thenwecoveredtemplatefilesandthepagestructureofthosefiles.Wealsocoveredthefunctions.phpfileindetail.Finally,weanalyzedthethemesubfoldersandfilesinit,includingsupportfortheJetpackpluginanditsfunctionality.

Inthenextchapter,wearegoingtostartcustomizingourthemefiles,suchasfunctions.phpandstyle.css,andmakingourthemeresponsive.

Chapter3.GettingStartedwithResponsiveLayoutBynow,youhavefamiliarizedyourselfwiththeWordPressthemearchitecture,howtoinstallandsetupWordPress,aswellassetuptheWordPressenvironment.

Now,wearegettingintomorefunstuff.

Inthischapter,wewillgetstartedwiththeresponsivelayoutandwewillcoverthefollowingindetail:

ChoosingtherighttoolforourprojectSettingupfunctions.phpSettingupstyles.cssSettingfontsSettingfonticonsAddingessentialscripts,suchasmodernizr.jsandrespond.jsAddingmediaqueries

ChoosingtherighttoolforourprojectBeforewebeginanalyzingandeditingthecode,weshoulddecidewhichIDEoreditorweshoulduse.Somepeopleonlyusetexteditors,andforthem,Irecommendthattheyusethefollowing:

Notepad++SublimeTextonWindowsTextMate,SublimeText,TextWranglerorBBEditonMac

IfyoupreferusingIntegratedDevelopmentEnvironment(IDE)toolsasIdo,thentherearethreetoolsinthemarketthatcanbeused,asfollows:

PhpStorm:Youhavetopayforthistoolbutit’swortheverypenny.PhpStormcanbedownloadedfrom:https://www.jetbrains.com/phpstorm/.NetBeans:Thistoolisavailableforfreeandcanbedownloadedfrom:https://netbeans.org/features/php/.PHPEclipse:Thisisalsoafreetool,whichcanbedownloadedfrom:http://www.phpeclipse.com/.

IhavetriedbothPHPEclipseandPhpStorm.PHPEclipseisafinetoolbutittakesalotoftimetoconfigure.Whenitisconfigured,itcanbebuggyassomefeatureswillnotwork.So,wewouldhavetogoonlineandsearchforfixes,andthiscantakesometime.Forexample,sourcecontrol(suchasGitorSVN)integrationisreallygoodinPhpStorm,whileitisjustokayinPHPEclipse.IwasworkingonaconsultingprojectandhadalotofproblemswithPHPEclipse.Mycolleague,whoisworkingforareputableWordPresscompany,toldmetotryPhpStorm.IwasresistantatfirstasPhpStormisnotfreebutwhenItriedit,Ineverlookedback.IjustgotthenewsletterlastmonthfromJetBrains(themakersofPhpStorm)andtheynowhaveafullWordPressintegrationinPhpStorm8.0.FormoreinformationonPhpStorm’sintegrationwithWordPressyoucan:https://confluence.jetbrains.com/display/PhpStorm/WordPress+Development+using+PhpStorm

ThenotablefeaturethatisinterestingistheWordPresscodingstyleortheWordPresscodingstandardssupport.WordPresshasitsowncodingstandardsthatarereallyrecommended,whichareshownasfollows,especiallyifyouareplanningtocreateathemeorplugin,soyourcodecanbeconsistentwiththeWordPresscoreandwiththecodefromotherdevelopers.

MoreinformationaboutWordPressCodingStandardsisavailablehere:

WordPressPHPCodingStandards(https://make.wordpress.org/core/handbook/coding-standards/php/)WordPressHTMLCodingStandards(https://make.wordpress.org/core/handbook/coding-standards/html/)WordPressCSSCodingStandards(https://make.wordpress.org/core/handbook/coding-standards/css/0)WordPressJavaScriptCodingStandards(https://make.wordpress.org/core/handbook/coding-standards/javascript/)

NoteNotethatwhenyousetupthecodestyle,Optionsworksonlywhenyoutypenewcode,whichisfine.Thereisanotheroption,PHPCodeSniffer,whichwillactuallyre-edityourcodeinordertomatchtheWordPressCodingStandards.

IfyouareplanningtosubmityourthemetoWordPress.org,IhighlyrecommendusingPhpStormwiththeWordPresssupportenabled.PhpStormhas30-daytrialoptionandmaybe,thistimewillbeenoughforyoutofinishtheprojectoratleasttotestthetoolproperly,asfollows:

SupportforWordPresshooks:HooksaretheoptionsthatallowacustompluginorthemetohookintotheWordPresscore.Thismeansthatthecorewillcallyourcustomfunctionalityandthreatisapartofit.SearchonWordPress.orgfromtheeditor:Itisagreatfeaturethatsavestimewhenopeninganewtaborwindowinabrowserandsearchingforstuff.IntegrationwithWP-CLI:It’stheWordPresscommand-linetool.Withthis,youcaninstall,enable/disableplugins,integration,andsoon.PhpStormalsohasagreatbuilt-inintegrationforJavaScripttechnologiessuchas,Sass,Less,Stylus,Compass,JavaScript,CoffeeScript,AngularJS,TypeScript,Emmet,andGrunt.Whatmorewecanaskfor!

SomeofmyfriendsareusingNetBeans,andtheyarehappywithit.Ijustdidn’twanttospendmoretimeonafreetoolwhenIcanuseapaidtoolthatworksperfectlyandsavesmealotoftime.

Howtosetupfunctions.phpWehaveanalyzedfunctions.phpindetailinthepreviouschapter.Now,wearegoingtodelvefurtherintoitandcustomizeittofulfillourneeds.

Infunctions.php,online12,thelineofcodeisshownas:

$content_width=640;

Here,wehavedefinedthesizeofthecontentpartinourpostsandpages.

Then,wealsochecktoseewhetherthetopcat_setupfunctionisalreadydeclaredsomewhereelse:

if(!function_exists('topcat_setup'))

Wehaveanalyzedthiscodepreviously,andweshouldalsomentionthatitenablesourthemetohavechildthemesandmakesourfunctionpluggable.Forexample,ifsomeonewantstocreatethechildthemefromourtheme,theycancreatethefunctionwiththesamenameinthechildtheme’sfunctions.phpfile.Thefunctionwilloverwriteourfunctions.phpfileasthechildtheme’sfunctions.phpfileprecedesourtheme’sfunctions.phpfile.

Online45,weshoulduncommentthefollowinglineasthisfeatureenablestheimagesupportintegratedinourtheme:

add_theme_support('post-thumbnails');

Online110,weshoulduncommentthiscode:

requireget_template_directory().'/inc/custom-header.php';

Here,thiscodeaddstheHeaderoptiontotheAppearancemenu(navigatetoAppearance|Header),whereausercanaddtheheaderimagetoourtemplateasshownhere:

Sincethisis2015,wewouldratherchoosecustomfontsthanbasicandoutdatedfonts.ThisiswhyIhavechosentwofontsforouruse:oneforheadings(OpenSans)andotheroneforcontent(Ubuntu).

Aswe’reusingcustomfonts,weshouldloadthethemefromsomewhere.Therearetwooptionstoconsider:

Firstly,tohavethefontsavailablelocally(withinourtheme).Then,toloadfontsfromanonlinerepositorylikeGooglefonts(thereareanumberofrepositoriesonline.GooglefontsisoneofthemostfamousbecauseoftheGooglebrand).

SincewearegoingtosubmitourthemetoWordPress.orgrepositoryandourthemehastopassthetests,wearegoingtousethefirstoption.Thisoptionisalsoabitbetterasthelocalfontswouldloadalittlebitfaster.

NoteNotethatfontsandCSSfilesareavailableintheCodefolderofthischapter,however,Iwillexplainhowwecanobtainthemanyway.

Firstly,wehavetodownloadthefontsandCSScodethatwillassignthesefontstothe@font-facevariable.InordertogetthefontsandCSScode,weshouldsearchforthefontfaceandnameonGoogle.Forexample,oneofthefontfacesiscalledOpenSans.Ifoundthefirstresultathttp://www.fontsquirrel.com/fonts/open-sans.Inordertodownloadboth,weshouldchoosetheWebfontKittabandclickontheDOWNLOAD@FONT-FACEKITbutton.Whenwedownloadthefonts,weshouldputthefontfilesinthefontsfolderandtheCSSfilesinthecssfolder.

TipAfontshouldhavemultiplefiles,sometimesinthreeormorefiles.

Forexample,considerthefollowingfiles:

OleoScript-Regular.eot

OleoScript-Regular.woff

OleoScript-Regular.ttf

OleoScript-Regular.svg

Inthiscase,therearefourfilesforthisfont.

Howdoweknowhowmanyfilesshouldbeinourdownload?

Toanswerthisquestion,weshouldopentheCSSfileattachedtoourdownload,andwewillbeabletoseethesefilenamesinit:

font-face{

font-family:'OleoScript';

src:url('../fonts/OleoScripRegular/OleoScript-Regular.eot');

src:url('../fonts/OleoScripRegular/OleoScript-Regular.eot?#iefix')

format('embedded-opentype'),url('../fonts/OleoScripRegular/OleoScript-

Regular.woff')format('woff'),url('../fonts/OleoScripRegular/OleoScript-

Regular.ttf')format('truetype'),

url('../fonts/OleoScripRegular/OleoScript-Regular.svg#OleoScript-

Regular')format('svg');}

So,foreachfont,weshouldhaveaseparateCSSfilewiththenameasthefontname(forexample,oleo-script.css),wherewedefineitas@font-face.Inourcase,wearegoingtouseonefontforheadings(OpenSans)andtwoforthecontent(UbuntuandOleoScript).

Then,weshouldaddthiscodeinthetopcat_scripts()function:

//fontfortheheadings

wp_register_style('topcat-headings-font',get_template_directory_uri().

'/css/open-sans.css');

wp_enqueue_style('topcat-headings-font');

//fontforthecontent

wp_enqueue_style('topcat-content-font',get_template_directory_uri().

'/css/ubuntu.css');

wp_enqueue_style('topcat-description-font',get_template_directory_uri()

.'/css/oleo-script.css');

TipDownloadingtheexamplecode

YoucandownloadtheexamplecodefilesforallPacktbooksyouhavepurchasedfromyouraccountathttp://www.packtpub.com.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.

Aswecanseefromtheprecedingcode,thefontfortheheadingshasmorecode.TheproblemisthatIwantedtousetheOpenSansfontthatisalreadyusedbytheWordPresscore,butourthemedidnotrecognizeit.Thesolutionforthisistoregisterourownfont.

Foricons,wewillusefont.awesomeandthiscodeshouldalsobeaddedtothetopcat_scripts()function:

//fontawesomeicons

wp_enqueue_style('topcat-fontawesome',get_template_directory_uri()

.'/css/font-awesome.min');

Sincewewanttobuildaprofessionaltheme,wewillalsohavetoaddsomescriptsthatwouldhelpusaddsupporttothelatesttechnologiesofolderbrowsers.Thesescriptsare:

modernizr.js

respond.js

ModernizraddsCSSclassestothe<html>elementforeachfeaturethattheuser’sbrowsersupports,forexample,borderradius.Forfeaturesthatabrowserdoesn’tsupport,ModernizraddsaCSSclassprefixofno-,forexample,no-borderradius.So,inourCSS,wecantargetunsupportedbrowsersandprovideafallbackusingeitherCSSorJavaScript.

Modernizrcanbedownloadedbyclickingonthedesiredlinkonitshomepage,available

at:http://modernizr.com/orwecanjustcallitfromContentDeliveryNetwork(CDN).

Modernizercanbedownloadedusingthesetwooptions:

DevelopmentuncompressedversionProductioncompressedversion

Itisrecommendedthatyougowiththedevelopmentoption,asitwillbeeasiertodebugifsomethingiswrong.Forfinalproductsorproductionwebsites,Icertainlyrecommendtheproductionversionsinceitiscompressedand,therefore,savessitesorpagesduringloadtime.Therearemanyoptionstochoosefromanditisrecommended,excludingthedefaultoptionsthatareselected.

Sinceweareloadingallthelocalscripts,weshouldloadModernizrwiththiscode:

wp_enqueue_script('topcat-modernizr',get_template_directory_uri().

'/js/modernizr.min.js',array(),false,false);

Now,respond.jsisthescriptthatenablesresponsivenessforoldbrowsersthatdonotsupportCSS3mediaqueries,forexample,IE8andolderversions.Wearegoingtoloaditfromalocalfile,too,asfollows:

wp_enqueue_script('topcat-respond',get_template_directory_uri().

'/js/respond.js',array(),false,false);

TipPleasemakesuretocopythecodeasitis,asthereareoptionswithenqueuescriptsthathaveJavaScriptcode,whichappearinthefooter.Thosetwoscriptsshouldbeinheader.

Thisisthewhatthetopcat_scripts()functionlookslikewhenallthecodeisadded:

functiontopcat_scripts()

{

wp_enqueue_style('topcat-style',get_stylesheet_uri());

wp_enqueue_script('topcat-navigation',get_template_directory_uri().

'/js/navigation.js',array(),'20120206',true);

//fontfortheheadings

wp_deregister_style('open-sans');

wp_register_style('topcat-headings-font',get_template_directory_uri()

.'/css/open-sans.css');

wp_enqueue_style('topcat-headings-font');

//fontforthecontent

wp_enqueue_style('topcat-content-font',get_template_directory_uri().

'/css/ubuntu.css');

//fontawesomeicons

wp_enqueue_style('topcat-fontawesome',get_template_directory_uri()

.'/css/font-awesome.min');

wp_enqueue_script('topcat-skip-link-focus-fix',

get_template_directory_uri().'/js/skip-link-focus-fix.js',array(),

'20130115',true);

wp_enqueue_script('topcat-modernizr',get_template_directory_uri().

'/js/modernizr.min.js',array(),false,false);

wp_enqueue_script('topcat-respond',get_template_directory_uri().

'/js/respond.js',array(),false,false);

if(is_singular()&&comments_open()&&get_option('thread_comments')

){

wp_enqueue_script('comment-reply');

}

}

So,makesureyoursourcecodematchesours,especiallythescriptsthatwehaveadded.

Howtosetupstyles.cssThestyles.phpfileiswhereourthemesettingsaresetandalsowherethestylesareset.Thefollowingimageshowsyouthethemesettingsthatwehavecoveredinthepreviouschapter;wehaveatableofcontentswhereeachsectionisshownasstylesarebrokendownintotwelvesections:

Wewillcoveronlytheessentialpartsthatweneedtochangehere.

TheResetsectioniswherethebrowsersdefaultstylesheetisoverriddenbecauseeachbrowserusesitsownstylesheetstodisplaythelayout.IfweloadthepagewithnoCSSresetinit,theHTMLelementswillbestyleddifferentlyindifferentbrowsers,sinceadefaultstylesheetisusedbyeachbrowser.ByusingtheResetCSS,wearemakingsurethatallthebrowsersarehavetheirdefaultstylessettotheinitialvaluesthataresetbyus,asshownhere:

Online60oftheprecedingscreenshot,font-family:inherit;andotherfontsinheritoptions.Thismeansthatthesesettingswillbeinheritedfromthebrowser’sdefaultstyle.

Online61,font-size:100%;meansthatthebrowserwillrenderthefontsizethatissetintheusersettingsofthatbrowser.Forexample,inFirefox,thedefaultfontsizeis16pixelsandyoucanseethesesettingsifyounavigatetoTools|Options|Content.Settingthefontsizeto100%makesourlifeeasierwithremandemvalues.

TheemandremvaluesHere,emisthecurrentfontsizefortheelementthatisassociatedtoit.Ifthefontisnotsetanywhereonthepage,thenthedefaultsizewillbe16pixels,asthisisthedefaultfontsizeforthebrowser;inem,itwillbe16pixelsaswell.

TipThemostpopularmethodusedwhenworkingwithemvaluesistosetthefontsizeonthebodyto62.5%.Sincethedefaultbrowserfontsizeis16pixels,thismakesit10pixels(withouthardsettingitto10pixels,whichwouldn’tcascade).Using10asamultiplierismucheasierthanusing16.Thisway,ifyouneedafontsizeof18pixels,useafontsizeof1.8em.

Whatisamultiplier?

Forexample,ifwehavethisCSScode{font-size:1.2em;}CSScode,that1.2isessentiallyamultiplierofthecurrentemvalue.So,ifthecurrentemsizeis10pixels,thelisttagisgoingtoturnouttobe12pixels.

Notethatinourstyle.cssthatweuseintheCSSResetsection,wesetthefontto62.5%:

html{

font-size:62.5%;/*CorrectstextresizingoddlyinIE6/7whenbody

font-sizeissetusingemunitshttp://clagnut.com/blog/348/#c790*/

overflow-y:scroll;/*Keepspagecenteredinallbrowsersregardlessof

contentheight*/

-webkit-text-size-adjust:100%;/*PreventsiOStextsizeadjustafter

orientationchange,withoutdisablinguserzoom*/

-ms-text-size-adjust:100%;/*

www.456bereastreet.com/archive/201012/controlling_text_size_in_shouldbe

together_for_ios_without_disabling_user_zoom/*/

}

So,wecancalculateourvalueseasilyas1emis10pixels,2emis20pixels,andsoon.Theproblemwithemisthatitcascades.Forexample,ifwehavetheemvaluesetforalisttobe1.2emandwehaveaparagraphwithinthislist,thefontsizeforthisparagraphwouldbe1.2em*1.2em.

HereistheCSScode,wherewesetthefontsizeforthelistandparagraphas1.2em:

li,p{

font-size:1.2em;

}

HereistheHTMLcodewherewenesttheparagraphwithinthelist:

<ul>

<li>list1</li>

<li><p>list1withparagraphinside</p></li>

</ul>

Theoutcomeforthisis:

Fromtheprecedingimage,wecanclearlyseehowthesecondlistwiththeparagraphhaslargerfonts.Thatistheresultofcascading.

Thisisaninstancewhereremcomestotherescue.Remisrootofem,orforsomepeople,itistherelativeemsizethatisrelativetothesizedefinedintherootHTMLelement.Thismeansthatifyouwanttoget16pixelsinaremvalue(thatis1.6rem),setthefontsizeto62.5%inResetCSS(asitisinthereset.cssfile)orfor18pixels,itwillbe1.8rem.

Wecanalsoseesomefixes/hacksfordifferentbrowsersfromline70through82,inthefollowingscreenshot,wheretextandotherhacksareapplied.Commentsbesidethecodeareexplainedthroughoutthiscodeinmoredetail:

TheunspokenruleisthatweshouldneverchangetheResetCSSandwewillfollowthisrule.

Sincethefontsareloadedaswehavecheckedourfilesearlier,weneedtosetthemforthecontentandtheheadings.

Wearegoingtodothisinthetypographysection:

Here,wehaveaddedourcustomUbuntufontinfrontofsans-serif.Wecanalsoseethatthefontsizedefinedinremandpixels.PixelsizesareusedasfallbackvaluesforolderbrowsersthatdonotsupportreminCSSsectionsforheaders:

WehaveaddedthecustomOpenSansfamily,withafontweightof800,andthefontcolorisblack.

NoteSincethelastcoupleofyears,developershavealsousedhue-saturation-light(hsl)valuesforcolorsthataremorecustomizable.Forexample,todefinethelightvalueofyourbluecolor.

Wewilladdseparatelayoutfilesforpagesthathavesidebar,andthosefilesarelocatedinthelayoutsfolderwiththecontent-sidebar.cssname(thismeansthatthecontentisontheleft-handsideandthesidebarisontheright-handside).

Weshouldaddthecalltoenqueuethatfileinthefunctions.phptopcat_scripts()functiononline97:

ThisiswhatthepagelookedlikebeforelayoutCSSfilewasadded.Notethatsidebaritems(suchasRecentPostsandRecentComments)arebelowthecontent,asshownhere:

ThisiswhatthepagelookslikeafterthelayoutCSSfilewasadded.Sidebaritems(suchasRecentPostsandRecentComments)areontheright-handside,asshownhere:

Thecodeforthisis:

.site-content.widget-area{

float:right;

overflow:hidden;

width:25%;

}

Wewillchangeitto:

.site-content.widget-area{

float:right;

width:30%;

padding-left:1rem;/*dejanadded*/

background:nonerepeatscroll00#f8f8f8;/**/

}

Here,wehaveleftthefloatoptiontoright,asthatishowthesidebarshouldfloat.Then,weaddedawidthof30%.Wehavealsosettheborder:1pxreddashedoption,sincewewanttoseewhat’sgoingonwithsidebar(whetherit’sgettingsqueezedornot)whenweresizethepage.Wehavealsoaddedthepadding-left:1remoptionforcosmeticpurposes.

Now,wearegoingtochangethecodeinthecontentarea.Thecodehereis:

.content-area{

float:left;

margin:0-25%00;

width:100%;

}

Itischangedto:

.content-area{

float:left;

width:70%;

border:1pxbluedashed;/*dejanadded*/

}

Wewillletthecontentfloatonleft,asitshould,andwewillalsohavewidthof70%forthecontent,sincethesidebaristakinganother30%.Fortestingpurposes,wewillhavethebordersetto1pxbluedashed.

Thisiswhatthetemplatewilllooklikewithdashedborders:

Fromthepreviousimage,wecanseethatthecontentareaistakesup70%ofthepageandthesidebartakesup30%oftheremainingspace.

AddingmediaqueriesOurfinalstepistoaddmediaqueries.Therearemanyapproachesforthisandwewillusethesimplestonetomakeourlifeeasier.Ourmediaquerieshaveonlythreecategories:

Mobilestyles(@mediaonlyscreenand(max-width:480px))Tabletstyles(@mediaonlyscreenand(min-width:481px)and(max-width:768px))Desktopstyles(@mediaonlyscreenand(min-width:769px))

Asyoucanseefromthepreviouscode,mobilestylesareforscreensupto480px,tabletstylesareforthescreensfrom481pxto768px(notethatthereisonepixeldifferencefrommobilestyles),andfinally,desktopstylesarefrom769px(notetheonepixeldifferencefromtabletstyles).

IfyouwanttouseamorecomplexboilerplateCSSwithmediaqueries,youcanfinditat:http://www.paulund.co.uk/boilerplate-css-media-queries(thisonesupportsbothportraitandlandscapemodesforpopulardevices).Fornow,Ihighlyrecommendthatyoufollowourbook.

Now,weshouldcutandpasteourcontentareaCSStoourdesktopmediaquery,asthatishowitshouldbehaveonadesktop:

/*desktopstyles*/

@mediaonlyscreenand(min-width:769px){

.content-area{

float:left;

width:100%;

border:1pxbluedashed;

margin-left:-300px;

padding-left:300px;

}

}

Whenweresizethescreentoatabletorphonesize,oursidebarwillstillfloatonright-handside,asshownhere:

Inordertofixthis,wewilladdthiscodetotabletandphonemediaqueries:

/*mobilestyles*/

@mediaonlyscreenand(max-width:480px){

.site-content.widget-area{

float:none;

width:auto;

}

}

/*tabletstyles*/

@mediaonlyscreenand(min-width:481px)and(max-width:768px){

.site-content.widget-area{

float:none;

width:auto;

}

}

Thefloat:noneoptionfixestheproblemandwidth:automakessurethatoursidebarwillonlytakeupthespaceitneeds.If,forexample,wehaveusedwidth:100%(asmanypeopledointhosecases),wewillhaveproblemifweaddthemarginorpadding,asthenoursection(inthiscasesidebar)willgobeyonditssize.Thewidth:autooptionmakessureitstaysinpropersize.Thecontent-sidebar.cssfileisavailableintheCodefolderofthischapter,soyoucancompareitwithyourchanges.

SummaryInthischapter,wegotstartedwiththeresponsivelayout,learnedhowtochoosetherighttoolforourprojectIDE,setupfunctions.phpandstyles.css,setfontsandfonticons,addessentialmodernizr.jsandrespond.jsscripts,andaddmediaqueries.

Inthenextchapter,wewilldiveintotheworldofheader,navigation,andsearch.

Don’twasteanytimeandstartwithChapter4,LearnHowtoCreatetheHeaderandNavigation.

Chapter4.LearnHowtoCreatetheHeaderandNavigationTheheaderismostlikelythefirstthingpeopleseewhentheylandonyourwebsite.Intoday’sworldwherethenextwebsiteisonlyaclickaway,youonlyhaveafewsecondstomakethelastingimpressions.

Navigationisalsothekeycomponentofeverywebsiteandthedesignofthewebsitenavigationhasahugeimpactonresults.Navigationislikearoadmapforthevisitorsofyourwebsite,showingthemthewaytogothroughthewebsiteandwheretheycanfindtheinformationtheyarelookingfor.

Thatiswhythisisprobablythemostimportantchapterinourbook.Grabbingtheattentionofpeopleclickingonyourwebsiteandeasilypointingthemtoyourwebsiteinformationisthegoalofeverywebsite,andcreatingthememorableheaderandusablenavigationissomethingthateverydesignershoulddo!

Areyouexcitedsofar?IknowIam.

So,let’sstart!

Inthischapter,wewilllearn:

HowtocreatetheheaderHowtocreateandstylethenavigationmenuHowtomakemenusaccessiblewithsuperfish.jsHowtomakemenusresponsive(makingthemlookgoodacrossalldevices)

MakingourlayoutcenteredBeforewedealwiththeheader,weneedtocustomizeourpagestyleinordertomakeeverythingcenteredonthepage,andwedothatbyaddingatopcat_pageclasstoline22inheader.php,asshown:

<divid="page"class="hfeedsitetopcat_page">

WealsoneedtoaddCSSforthisclassincontent-sidebar.css:

.topcat_page{

background:nonerepeatscroll00#fff;

box-sizing:border-box;

margin:0pxauto0!important;

max-width:1000px;

border:1pxblackdashed;

}

Themostimportantpartsofthiscodeare:

margin:0pxauto0!important;:Thiscodemakesourcontentcentered.max-width:1000px;:Thiscodemakesourcontenthaveamaximumwidthof1000pixels.

Ihavealsocreatedthebordertobeblackanddashedwiththeborder:1pxblackdashed;codesothatwecandistinguishthissectionfromothers,asshownnext:

DealingwiththeheaderHereistheimageoftheheaderofourcurrentTopCat:

Let’sanalyzeeachnumberedsection:

Section1isourlogo.Section2isthemenuforwhichwewillchangethelookandthestructure.Section3isjustanadvertisementandthecontactinformation.Wewillputthetagline(description)there.

NoteThetaglinecanbefoundandsetinwp-adminbynavigatingtoSettings|General.

Insection4,wehavethephoneimagethattakescustomerstoourcontactpage.Wewilltakethisoneout,aswewillhaveacontactuslinkinthemenu.Insection5,wehavesocialiconsthatwillstayinthetop-rightcorner.

Aswehavementionedpreviously,theheaderforWordPresswebsitesishandledbytheheader.phpfile.Inthatfile,first,wehaveanHTMLmarkupthatanyHTMLpagehasandthatismostlytheHTMLheadandmetatags.Then,wehavethewp_head();call,andthisfunctioncallisactuallycallingwp_enqueue_styles()andwp_enque_scripts()thatwehavesetinthefunctions.phpfile,asyoucanseeinthefollowingscreenshot:

Afterthis,theinterestingstuffcomes,asyoucanseefromthefollowingscreenshot::

Let’stakealookatit:

First,wehaveabody_class();call,andthisisthefunctionthataddsspecificclassestothe<body>tagbasedonwhereonthesiteyouareinrelationtotheWordPresstemplatehierarchy.

NoteWecanpassourownclassesbypassingmyclassasanargumenttothefunctioncall.

Moreinformationisavailableathttp://codex.wordpress.org/Function_Reference/body_class

Lateron,online23.wehavea“Skiptocontent”link.Thisisthelinkforscreenreaderstohelpuserswhouseascreenreaderjustskiptocontent,andnottohavetolinkthroughthemenu.Then,wehaveasitetitlecodeonline27andsitedescription/taglineonline28.Lateron,fromline31till34,wehaveacalltothemainnavigation(mainmenu).

Asthenumberoneisthelogoonourfirstimage,weshouldstartfromthere.Inourcode,inthepreviousscreenshot,wedon’thavetheimageoption.However,wehadalreadyimplementedacustomheaderoptioninthepreviouschapter,andwejusthavetoaddthecodefortheimagefunctionalitytoourheader.phpfile.Thiscodeisavailableinthecustom-header.phpfile,asshownnext:

Now,let’scopythiscodetoourheader.phpfile.

NoteAsIdon’twanttodisplaythesitenameonthisoccasion,I’venestedthiscodeinthesitename’slinkcode.

Thecopiedcodeisasfollows:

<ahref="<?phpechoesc_url(home_url('/'));?>"rel="home">

<?phpif(get_header_image()):?>

<ahref="<?phpechoesc_url(home_url('/'));?>"

rel="home"><imgsrc="<?phpheader_image();?>"width="<?phpechoesc_attr(

get_custom_header()->width);?>"height="<?phpechoesc_attr(

get_custom_header()->height);?>"alt=""></a>

<?phpendif;//Endheaderimagecheck.?></a>

Whentheuserclicksonthelogo,he/shewillbetakentooursite’sroot/indexpage.Beforeweuploadtheimage,weshouldsettheimagesizeinourcustom-header.phpfileonlines29and30asyoucanseeinthefollowingimage.

NoteOurlogoislocatedinthechpt3directorywiththeimagethathasalogo.jpgname.Logo’ssizeis150x250,andweshouldputthesevaluestothewidthandheightoptions,respectively.

Inordertoseeourimage,wehavetogotoAppearance|Headerinwp-adminandthengototheSelectimageoptionanduploadit.

TipYoucanuploadyourownimageifyouwant,butmyrecommendationisthatyoufollowourbookfornow,andthenlateron,ifyouwant,youcanchangetheimage.

Ifyoudecidetouseyourimageandit’sadifferentsizethanwhat’sthereinthecustom-header.phpfile,youwillgettheoptiontocroptheimage.Whenyouuploadtheimage,thisishowyourheadershouldlooklike:

Aswecansee,section#1containsthelogo.Thetaglineisinsection#2andthemenuisinsection#3.

Aswecanseeinthepreviousscreenshot,thesite’sdescription(tagline)isunderthelogo.Thisisfineformobiledevices,butIrecommendthatyouadd.site-description{display:inline;}inthemediaqueryfortabletsanddesktops.Thisway,thesite’sdescriptionisdisplayedontheright-handsideofthelogoexactlythewaywewant.Aswealsowanttomakethesite’sdescriptioncenteredonthepage,first,wehavetodealwiththesite-brandingsection,asit’saparentsectionofthesitedescription:

.site-branding{

position:relative;

border:1px#008000dashed;

}

Thiscodemakespositionrelativetothesitebranding.

NoteIhavecreatedagreendashedborderforittobeabletodistinguishitothersections.

Then,inordertomakethesitedescriptioncentered,wehavetoaddthefollowingcode:

.site-description{

display:inline;

position:absolute;

bottom:0px;

left:25%;

padding:1em0;

/*border:1pxorangedashed;*/

}

Theleft:25%propertyismakingthesitedescriptioncentered.Thepadding:1em0;propertyispushingitupalittlebitaswell.

TipAsIliketodesignmylayoutsmoreincodethaninPhotoshopandasit’smorerealistictome,thesevaluesmaychangelateron.

Ihavealsoaddedthetestcodeforthesocialmenuinthetop-rightcornerintheheader.phpfile:

<divclass="social-menu">Socialmenuhere</div>

Incontent-sidebar.css,Ihaveaddedthis:

.social-menu{

display:inline;

position:absolute;

top:10%;

right:5%;

}

Wewilltacklethesocialmenulateronwhenwedealwiththemainmenu.

Hereisthecurrentlookofourheader:

HowtocreateamenuandmakeitresponsiveandaccessibleHereisthecurrentlookofourmenuonthedesktopscreen:

Now,let’slookatourmenuonthemobilescreen:

Asyoucansee,thecodefromunderscores(_s)changesthelookautomaticallywhenwechangethescreensize,butwestillhavesomeworktodo.

MenubasicsOurmainmenuisdefinedinthefunctions.phpfilefromlines43through46:

//Thisthemeuseswp_nav_menu()inonelocation.

register_nav_menus(array(

'primary'=>__('PrimaryMenu','topcat'),

));

Then,themenusectionsaredefinedinAppearance|Menus.IfyougotoManagelocationsinthissection(thesecondtabintheheader),youwillbeabletochangetheassignedmenuoptions.

Inordertoseethemenu,wehavethiscodeinheader.php:

<?phpwp_nav_menu(array('theme_location'=>'primary'));?>

Thiscallstheprimarymenufromthethemelocation.

StylingourmenuDealingwiththemenuisoneofthemostimportantpartsintheWordPressthemedevelopment,asthemenuitselfisoneofthemostimportantpartsofanywebsite.Thankstounderscores(_s)anditsarchitecture,allCSSclassesarealreadycoveredandweonlyhavetoaddproperstylestothem.Ourmenuisnestedinthenavigationtagwiththemain-navigationclassandthat’stheclassthatwearegoingtoeditfirst.Thisclassislocatedinstyle.css:

.main-navigation{

font-family:'Open+Sans',sans-serif;

font-weight:800;

float:left;

width:100%;

position:relative;

display:block;

clear:both;

text-transform:uppercase;

background:#0480b5;

}

Inthiscode,weareaddingtheOpen+Sansfontfamily(thesamefontfamilythatweareplanningtouseforheadingsthroughoutourtheme).Afterthat,wearesettingthefontweightto800tomakethefontsbolderthantheyare.Lateron,wearefloatingittotheleftandsettingthewidthofthecontainerto100%inordertomakesurethatthiscontainertakes100percentofspace.Wearealsosettingthecontainertodisplay:blockinordertomakesurenothingelsegoesonthesideofthemenu.Lateron,weareexecutingclear:both,aswewereusingfloats(float:left;)previouslyandweneedtoclearthem.Finally,weoursettingourtexttouppercaseasit’samenutext,andthenwesetourbackgroundtoourbluecolor(background:#0480b5;).

Thisishowourmenulookslikeafterthesechanges:

Now,wehavetochangethelookofourlinks,andwewilldothatwiththe.main-navigationaclass/selector:

.main-navigationa{

font-size:15px;

font-size:1.5rem;

display:block;

text-decoration:none;

color:white;

padding:14px10px;}

Inthisclass,wearesettingthefontsizeof15px,asithelpsourmenustandout.Wearealsousinga1.5remsizefornewbrowsers,as15pxisactuallytheonlyfallbackvalueforoldbrowsers.Lateron,wewilldisplaytheblocksettingsmentionedinthepreviouscode.

Afterthat,wehavethetext-decoration:none.Weneedtousethisbecauseourmenuitemsarelinksandwedon’twanttohaveunderlinesbelowthem.Then,wesetthelink/itemscolortowhite,andfinally,wesetthetopandthebottompaddingto14pxandtheleftandrightpaddingto10px.Hereisthelookofourmenunow:

Itlooksawesome,right?Wejustsetthemainlevel,andinthenextstep,wewillstylethedropdowns.Inordertoseehowdropdownslooknow,hoveraboutthetestssection,asshowninthefollowingscreenshot:

Aswecanseeinthepreviousscreenshot,thereisaPAGEIMAGEsublinkandotherthingsunder,asdropdownsarenotdefinedyet.Weshouldchangesomecodeforthedropdowninthe.main-navigationululclass/selector:

.main-navigationulul{

/*box-shadow:03px3pxrgba(0,0,0,0.2);*/

float:left;

position:absolute;

top:3.1em;

left:-999em;

z-index:99999;

background:#579DB5;

}

Inthepreviouscode,I’vecommentedoutthebox-shadowproperty,settopto3.1em,andchangedbackgroundtolight-blue(background:#579DB5;).

Nowwewanttogetthecodethatwillchangethebackgroundcolorwhenwehoveroverthenavigationitems:

.main-navigationli:hover>a{

color:#fff;

background:#579DB5;

}

Thenavigationitemlookslikethisafterthemodifications:

Wearemakingsurethatthemaincolorforfontsiswhiteandthatweareputtingourbackgroundaslightblue.

Withthefollowingcode,wewillchangethebackgroundcolorinthehoverforsubmenuitems,whichshouldbethesameasourmainbackgroundcolorsetinthe.main-navigationclass:

.main-navigationulula:hover{

background:#0480b5;

}

Thesubmenuitemslookasfollowsnow:

Thelastpartofourcodeshouldmark/highlightthecurrentpage(thecurrentlyactivepage)inourmenu:

.main-navigation.current_page_item>a,

.main-navigation.current-menu-item>a,

.main-navigation.current_page_item>a:hover,

.main-navigation.current-menu-item>a:hover{

background:#579DB5;

}

Thepreviouscodehighlightsthecurrentpageinthemainmenu.Thefollowingcodehighlightsthepageancestor:

.main-navigation.current_page_ancestor{

background:#579DB5;

}

Ifsomeonehashighlightedthesubpageandwegothroughthemenu,wewillseethatpagehighlighted.Inthethird(final)part,weareapplyingthemainbluecolor,soifsomebodyselectsasub-itemfromasubmenu,thatwillbeinthedarkercolor,andthisway,itwillbemoredistinguishedfromothersubmenuitems:

.main-navigationulul.current_page_parent,

.main-navigation.current_page_parent.current_page_item>a{

color:#fff;

background:#0480b5;

}

Afterallthemodifications,thenavigationmenulookslikethis:

Asyouprobablynoticed,whenwehoveroversomesubmenuandthenitssubitems,ourmenuhidesveryquickly,andthismakesourmenualmostunusable.Inthenextsection,wewillmakeourmenuaccessible,andthiswillalsosolveourproblemwithclosingouritemstoofast.

HowtomakeourmenuaccessibleAswecan’taccesssomesubmenuitemsbecausethemenuclosestoofast,wewanttomakethemenuaccessibleforthepeoplewhouseonlykeyboard,orsomeotherdevice,sothattheycanaccessthemenunormally.Forthispurpose,wewillusetheSuperfishjQueryplugin,whichisavailableat:http://users.tpg.com.au/j_birch/plugins/superfish/download/.

Pleasedownloadthearchiveandunpackit.Thereisabunchoffilesandfoldersthere,andweonlyneedsuperfish.min.js,whichisavailableatdist/jsfolder.Inordertousethis,weshouldcopyandpastethatfileinourtheme’sjsfolder.Now,weshouldloadthatfilethesamewaythatweloadother.jsfiles,andwearedoingthatwithwp_enqueue_scriptinthefunctions.phpfile:

wp_enqueue_script('topcat-superfish',get_template_directory_uri().

'/js/superfish.min.js',array('jquery'),'20141123',true);

TipWeshouldputthiscodeaboveallJavaScriptwp_enqueue_scriptcalls.

Inthepreviouscode,wehavetopcat-superfish,whichisthereferencename,wehavethefilelocation(get_template_directory_uri().'/js/superfish.min.js'),andwehavearray('jquery')—thispropertysaysthatthiscodeneedsjQueryinordertorun(thereisjQuerydependency).Then,'20141123'isaversionnumber(I’veputacurrentdate),andfinally,truemeansthatthisJavaScriptcallshouldbeplacedinthefooter.So,let’srefreshthepageandcheckwhetherwecanfindthislineinourfooter:

<scripttype='text/javascript'src='http://localhost/topcat/wp-

content/themes/topcat/js/superfish.min.js?ver=20141123'></script>

WenowneedtowireSuperfishtoourmenu.Inordertodothat,wewillcreateanothercustomJavaScriptfilewherewewillwireittoourmenu.So,let’screatetheglobal.jsfileinourtheme’s.jsfolderandwp_enqueue_scriptinourfunctionsfilejustbelowSuperfish’swp_enqueue_script()call

wp_enqueue_script('topcat-global',get_template_directory_uri().

'/js/global.js',array('topcat-superfish'),'20141123',true);

Thecodeisalmostthesameasthepreviousone.TheonlydifferenceisthatnowthedependencyisonSuperfishinsteadofjQuery.Finally,wehavetowireourcustomSuperfishtoourmenu,andwedothatwiththiscode,whichshouldgotoglobal.js:

jQuery(document).ready(function($){:

varsfvar=$('div.menu');

sfvar.superfish({

delay:500,

speed:'slow'

});

});

Intheprecedingcode,wearewiringSuperfishtoouroutmostmenuitem,whichisdiv.menu.Then,wesetdelay:500,whichdetermineshowlongthemenuwillstayopen

(tofixourpreviousproblem)ifwemovethemousefromthemenu.Thespeed:'slow'propertyissetfortheopeninganimation(theopeningofsubmenuitems).

HowtomakeourmenuresponsiveOurmenulooksgoodonadesktopscreenbutwehavetodosomeworkformobilescreens.Hereisthelookofourmenunowifweresizethebrowser:

Intheprecedingscreenshot,wecanonlyseethewordMENU,andthatisnotagooduserexperience.Becauseofthat,weneedtochangethecodeinthe/*Smallmenu*/sectionofstyle.css,whereitsays@mediascreenand(max-width:600px),whichmeansthecodeinsideofthemediaquery.Thecurrentcodeisasfollows:

.menu-toggle,

.main-navigation.toggled.nav-menu{

display:block;

}

.main-navigationul{

display:none;

}

Thiscodeismakingtogglepartablockelement,anditishidingulinthemainnavigation.So,let’sdeletethispartfirst:

.main-navigationul{

display:none;

}

Next,weneedtoaddthiscode:

.main-navigationulul{

display:block;

width:100%;

float:none;

position:relative;

top:inherit;

box-shadow:none;

height:auto;

margin:0;

}

.main-navigationulula{

width:100%;

}

Inthefirstsection,wearemakingnavigationelementsasblockelementsaswiththemobilemenu,theyshouldallhavetheirownlines.Inthesecondpart,wearegivingallsub-elementsthewidthof100%.Let’sseehowourmenulooksnow:

Thislooksalotbetterthanbefore,butourmenuelementsstillaren’tinoneverticallineaswewant.Hereisthecodethatwillmakethispossible:

.main-navigationli{

float:none;

position:relative;

}

Withthiscode,weareresettingourfloatsandhereisthenewlook:

Aswecansee,itlooksalotbetteralready.

Theonlyissuenowisthatifwehoveroverthelinksthathavechildren,wehavetheSuperfishanimation.So,weshoulddisableSuperfishforsmallerscreens,asfollows:

varsfvar=jQuery('div.menu');

varphoneSize=600;

jQuery(document).ready(function($){

//ifscreensizeisbiggerthanphone'sscreen(Tablet,Desktop)

if($(document).width()>=phoneSize){

//enablesuperfish

sfvar.superfish({

delay:500,

speed:'slow'

});

}

$(window).resize(function(){

if(body.width()>=phoneSize&&!sfvar.hasClass('sf-js-enabled')){

sfvar.superfish({

delay:500,

speed:'slow'

});

}

//phoneSize,disablesuperfish

elseif((document).width()<phoneSize){

sfvar.superfish('destroy');

}

});

});

Let’sanalyzethepreviouscode

First,wearesettingasfvarvariabletodiv.menu,asourmenubeginsonthistag(div.menu).Then,wearesettingaphoneSizevariablethatgetsthevalueof600,whichisthebreakpointforasmall/phonemenu.Afterthis,wearecheckingwhethertheHTMLscreen’swidthisbiggerthanaphonescreen,andifitisbigger,thenweactivateSuperfish.Thenextcodeischeckingwhetherthescreenhasbeenresized,fromthephonesizetothedesktopsize.Ifithasbeen,itwillenableSuperfish,andifthescreenwasresizedfromthedesktopsizetothephonesize,Superfishwillbedisabledbyusingsfvar.superfish('destroy');.

SummaryInthischapter,wehavestyledourheadings,andthenwehavecreatedourmainmenuandimplementedaccessibilityfeaturesinit.Ourmenuwouldnotbecompleteifwedidn’tmakeitresponsive,andwedidthattoo.

Inthenextchapter,wewilllearnaboutposttemplatesbycustomizingthemandmakingthemresponsiveaswell.

Chapter5.CustomizingSinglePostTemplatesInthischapter,wewillworkonposttemplatesandtheircomponents,suchastitle,meta,andnavigation.Singleposttemplatesareusuallyusedforblogposts.Theyhelpussetupabasiclayoutthatwecanextendlaterwithindextemplatesandstaticpages.

Wewillcoverthefollowingtopics:

CustomizingtemplateelementsMakingtemplateelementsresponsive

Inordertounderstandallthesetemplatetypes,wecanusethefollowingimageasareference:

Source:http://codex.wordpress.org/images/9/96/wp-template-hierarchy.jpg

AnalyzingsingleposttemplatesForsingleposttemplates,asingle.phpfileisusedasastart-upfile,anditisonlyabootstrapfile.Thecontentofasingle.phpfileisasfollows:

?php

/**

*Thetemplatefordisplayingallsingleposts.

*

*@packagetopcat

*/

get_header();?>

<divid="primary"class="content-area">

<mainid="main"class="site-main"role="main">

<?phpwhile(have_posts()):the_post();?>

<?phpget_template_part('content','single');?>

<?phptopcat_post_nav();?>

<?php

//Ifcommentsareopenorwehaveatleastonecomment,loadup

thecommenttemplate

if(comments_open()||get_comments_number()):

comments_template();

endif;

?>

<?phpendwhile;//endoftheloop.?>

</main><!--#main-->

</div><!--#primary-->

<?phpget_sidebar();?>

<?phpget_footer();?>

Atthebeginningofthefile,thereisacalltotheget_header()function,whichcallstheheader.phpfile.Inmoredetail,thisfunctiontypicallycallstheHTMLtitle,head,andothernavigationelementsthatexistthroughoutthesite—theitemsthatshouldappearoneverypageintheheadersection.

Lateron,wecheckwhetherthereisapostwiththewhile(have_posts()):the_post();code,andifthereis,weloadthecontent(partofthepagefromcontent-single.php)withtheget_template_part('content','single');code.

Thefollowingscreenshotshowsasamplepage:

Inordertobetterunderstandwhatcontentis,let’sanalyzetheprecedingimage:

Thefirstsection(#1)istheheaderThesecondsection(#2)isthemenuThethirdsection(#3)isthesidebarThefourthsection(#4)isthepostnavigationThefifthsection(#5)isthecontentpart

Afterthis,weloadthepostnavigationwiththetopcat_post_nav()functioncallandthenloadcomments:

if(comments_open()||get_comments_number()):

comments_template();

endif;

Ifcommentsareenabledandtheyexist(somebodyhasalreadypostedacomment),wecallthesidebarandthefooterattheendofthecode.

Notethatforthissection,wewilluseaTemplate:Stickypost.Asthisisthefirstpostthatappearsunderournavigation,it’seasytomanage.

TipWhenyoumarkthepostasastickypost,itwillalwaysloadfirst,nomatterwhenitwascreated.Afteritisloaded,otherpostswillshowuponthepost’sindexpage.

Tomakethepoststicky,gotooneofthepostsinthePostssectioninwpadminandunderthePublishsection(top-rightcorner),checktheStickthisposttothefrontpageoption.

WeneedtoclickontheEditlinkintheVisibility:section(step#1)toseetheStickthisposttothefrontpageoption(step#2),asyoucanseeithere:

Bydefault,theVisibilityitemofthePublishsectionisclosed/collapsed.

Sinceweareusing“Themeunittestdata,”thereisapostwiththenameTemplate:Sticky,whichisalreadysettobesticky,asyoucanseeitfromthefollowingimage:

TofindtheTemplate:Stickypostinourdatabase,weneedtogotothePostssectionofwpadminandthensearchforit,asshowninthefollowingscreenshot(step#1):

Asaresult,wewillgetthepostnameshowninstep#2ofthepreviousscreenshot.

NoteIfwearenotsurewhethertheoptionisworking,tryuncheckingtheStickthisposttothefrontpageoption,checkthemainpage(ifthatpostisnomorethefirstpostonthepage),andcheckitagain(nowitshouldbethefirstpostagain).

InWordPress,thereisanoptiontoenable/disablecommentsforeachpost.Inordertoseewhethercommentsareenabledordisabled,weneedtogotoourpostandthenclickonScreenOptionsontheheader,asshowninthenextscreenshot:

Then,clickonthediscussionbox,asshownhere:

TipThereisalsoanoptionnamedAllowcommentstoenable/disablecommentsonallpostsinthegeneralsettings.ThisisundertheDiscussionsection(Settings|Discussion).

Afterthis,theDiscussionsectionwillappearunderoureditorsection,andtherewewillseetheoptiontoenable/disablecomments,asshowninthefollowingimage.

Analyzingthecontent-single.phpfileNowthatwe’velookedatsingle.php,whichisthecontainerforsinglepagesofvarioustypes,let’slookatcontent-single.php,whichiswherethepostcontentitselfgetsrendered:

<articleid="post-<?phpthe_ID();?>"<?phppost_class();?>>

<headerclass="entry-header">

<?phpthe_title('<h1class="entry-title">','</h1>');?>

<divclass="entry-meta">

<?phptopcat_posted_on();?>

</div><!--.entry-meta-->

</header><!--.entry-header-->

<divclass="entry-content">

<?phpthe_content();?>

<?php

wp_link_pages(array(

'before'=>'<divclass="page-links">'.__('Pages:','topcat'),

'after'=>'</div>',

));

?>

</div><!--.entry-content-->

<footerclass="entry-footer">

<?phptopcat_entry_footer();?>

</footer><!--.entry-footer-->

</article><!--#post-##-->

First,let’sanalyzewhateachpartofourcoderendersvisuallyonasinglepostpage,andlateron,wewillanalyzetherenderedmarkup(HTML),too.Forthis,weneedtogotohttp://localhost/topcat/title-with-special-characters/.

TipIfyouarenotworkingonalocalhost,pleasechangethehostnamelocalhosttothe

hostnameofyourenvironment.

Thefollowingcodeprintsouttheposttitle(#1intheprecedingimage):

<?phpthe_title('<h1class="entry-title">','</h1>');?>

Thiscodeprintsoutthemeta-informationforasinglepost(#2inthepreviousimage):

<divclass="entry-meta">

<?phptopcat_posted_on();?>

</div>

Thefollowingcodeprintsoutthepostcontent(#3intheprecedingimage):

<divclass="entry-content">

<?phpthe_content();?>

<?php

wp_link_pages(array(

'before'=>'<divclass="page-links">'.__('Pages:','topcat'),

'after'=>'</div>',

));

?>

</div><!--.entry-content-->

Thefollowingcodeprintsoutthefooter(#4inthepreviousimage):

<footerclass="entry-footer">

<?phptopcat_entry_footer();?>

</footer><!--.entry-footer-->

Now,let’sanalyzetherenderedmarkup(HTML)thatwegotfromourcode,astherearealotofotherthingsgoingonunderthehood.

Inthefirstlineofthecontent-single.phpfile,wehaveanarticletagwithanIDandclass.TheIDiscreatedfromthewordpost-andthepostIDthe_ID();theclassisgeneratedfromthepost_class()function.TherenderedHTMLlookslikethis:

<articleclass="post-1241posttype-poststatus-publishformat-standard

hentrycategory-uncategorizedtag-sticky-2tag-template"id="post-1241">

Aswecanseefromtheprecedingcode,therearesomanyclassesthatwecanutilizeinordertoreachourgoals.TheseclassesallowustouseCSStotargetspecificposttypes,posts,statuses,andformatsinordertochangetheappearanceoftheseposts,suchasthefollowing:

post-1241:Accessonlythe1241postpost:Accessallthepoststype-post:Accessthecontentofatypepoststatus-publish:Accessanycontentthathasitsstatusaspublishedformat-standard:Accessanycontentthathasthestandardpostformat

TipInasophisticatedsoftware,suchasPhpStormorNetBeans,youcaneasilyinspectthefunctioncalljusttoseethedeclarationofthefunctionorclass.Forexample,wecanright-

clickonthecodeonapost_class()callandgotoGoTo|Declaration.Thenwewillbeabletoseetheinsidesofthefunction.Isn’tthatcool?

ThisisthescreenshotfromthePhpStormIDE.

PostFormatisapieceofmetainformationthatcanbeusedbythemetocustomizeitspresentationofapost.ThePostFormatsfeatureprovidesastandardizedlistofformatsthatisavailabletoallthethemesthatsupportthefeature.Themesarenotrequiredtosupporteveryformatonthelist.Inshort,withathemethatsupportsPostFormats,abloggercanchangethelookofeachpostbychoosingaPostFormatfromtheradiobuttonlist.

PostFormat(ifsupportedbythetheme)canbechangedinthewpadminpageofeachpostorpage.Itcanbefoundontheright-sidewidgetcalledFormat,asyoucanseefromthefollowingimage:

Thefollowingistheresult:

functionpost_class($class='',$post_id=null){//Separatesclasses

withasinglespace,collatesclassesforpostDIVecho'class="'.join('

',get_post_class($class,$post_id)).'"';}

Aftercodeinarticletag,wehavethethe_title()function,whichprintsthetitleonthescreenandusesh1withtheentry-titleclass.Justafterthis,wehavetopcat_posted_on,whichprovidesthedateandbywhomitwaspostedinformation,suchas“PostedonJanuary7,2012,bytheadmin.”Lateron,wehavethethe_content()call,whichgetsthepostscontent;afterthis,wehavethewp_link_pages()functionthatprovidestheprevious/nextlinks(thisistheprevious/nextpageofapaginatedpost).

Therearetworeasonswhyyouwillliketousepaginatedposts:

PageviewsareveryimportantforSearchEngineOptimization(SEO).Ifwesplitthepostsintomultiplepages,wewillincreasepageviewsforourwebsiteandourwebsitewillrankbetterwithsearchengines.

NoteApageview(PV)orpageimpressionisarequesttoloadasingleHTMLfile(webpage)ofanInternetsite.OntheWorldWideWeb(WWW),apagerequestwouldresultfromawebsurferclickingonalinkonanotherpagepointingtothepageinquestion.Thiscanbecontrastedwithahit,whichreferstoarequestforanyfilefromawebserver.Theremay,therefore,bemanyhitsperpageviewsinceanHTMLpagecanbemadeupofmultiplefiles.Onbalance,PVrefertoanumberofpagesthatareviewedorclickedonthesiteduringthegiventime.

Ifwehavealotoftextinthepostandthereisaprobabilitythatuserswillnotreadthewholepostatonce,itwouldbebettertosplitthepostintomultiplepages.So,readerscanbookmarkthepagewheretheyhavestoppedreadingandcontinuelaterfromthere.

Then,wehavethetopcat_entry_footer()callforafunctionthatisdeclaredininc/template-tags.php.Let’sanalyzethecodenow:

functiontopcat_entry_footer(){

if('post'==get_post_type()){

$posttags=get_the_tags();

echo'<divclass="tags-links">Tags:<span>&nbsp;&nbsp;';

if($posttags){

foreach($posttagsas$tag){

echo'<iclass="fafa-tag"></i>&nbsp;&nbsp'.

'<ahref="'.get_tag_link($tag->term_id).'">'.

$tag->name.'</a>&nbsp;&nbsp';

}

}

echo'</span><div>';

}

if(!is_single()&&!post_password_required()&&(comments_open()||

get_comments_number())){

echo'<spanclass="comments-link">';

comments_popup_link(__('Leaveacomment','topcat'),__('1

Comment','topcat'),__('%Comments','topcat'));

echo'</span>';

}

}

Aswecanseefromtheprecedingcode,wewanttodisplaythetagsintheposts(astagscanonlybeassignedtopostsnotpages).Ourcodecheckswiththeifstatementwhetherthepageisapostornot.Ifit’sapost,itwillprintoutcategoriesandtags.Lateron,itcheckswhetherit’sasinglepostpage(whichmeansit’snotarchived).

TipArchiveposts/pageslistorindexanumberofpostsonapage,andusually,theydisplaytheposttitle,metacategoriesandmetatags,andexcerptsfromthecontent.Singlepostpagesdisplayeverythingmentionedpreviously,plusthefullcontentinsteadofexcerpts,andcommentstooifenabled.

TemplateimprovementsWehaveanalyzedthecodeandnowit’sthetimetomakeourchanges.AsIsaidpreviously,anumberofdevelopers,includingmyself,nowliketodesigninabrowser.Thisisbecausewhenyouinteractmorewithyourdesign,yougetbetterideasandwanttoimprovemore.Ontheotherside,youshouldbecarefulnottogointhefeaturecreepstate.

TipFeaturecreepisastatewhereyouoryourcustomersfeellikeaddingmorefeatures,andthisroadthendoesn’tendeasily.Myrecommendationistomakechangesonlyifyouthinktheywillimprovethedesignandusabilityofthesite,butatthesametime,becarefulabouthowmanychangesyoumakeasyouneedtofinishyourprojectontime.

Inourcase,weneedtofinishourthemeandsubmitittoWordPress.orgassoonaswecan.Lateron,wecanmakechangesandupdates.

HeaderimprovementsIhaveaddedasilverbackgroundcolorinordertodistinguishthebackgroundfromthecontentofthesite.Thischangeshouldbedoneinthestyle.cssfile’sContentsectionbyaddingthiscode:

body{

background:nonerepeatscroll00#e6e9ed;

}

Nowthatwecanclearlydistinguishthesections,weshouldcommentoutthebordersincontent-sidebar.css:

.topcat_page/*border:1pxblackdashed;*/

.site-branding/*border:1px#008000dashed;*/

.site-content.widget-area/*border:1pxreddashed;*/

Afterthat,Ihavedecidedtogivealittlespacetotheheaderlogothatlookslikethis:

Aswecanclearlyseefromthepreviousimage,thereisnospaceontheleftsidebythe

border.Thesolutionistoadddivwiththelogo-containerclassaroundourlogotoheader.php:

<divclass="logo-container">

<?phpif(get_header_image()):?>

<ahref="<?phpechoesc_url(home_url('/'));?>"rel="home"><img

src="<?phpheader_image();?>"width="<?phpechoesc_attr(

get_custom_header()->width);?>"height="<?phpechoesc_attr(

get_custom_header()->height);?>"alt=""></a>

<?phpendif;//Endheaderimagecheck.?>

</div>

I’veputalogo-containerclassinourstyles.cssfileinthenewsection13.HeaderthatIhavecreated:

/*--------------------------------------------------------------

13.Header

--------------------------------------------------------------*/

.logo-container{padding:0px10px;}

Withthischange,ourlogoimageismovedalittlebittotheright:

Undertheheadersectioninstyles.css,wecancreateanothersection14.Colorswherewecanstoreourcolorpalettevalues:

*--------------------------------------------------------------

14.Colors

--------------------------------------------------------------*/

/*ourblue#0480b5;*/

/*ourbluelight#579DB5;*/

NoteThecommentsareaddedbymeandtheydon’trenderanything,astheyareherefortheinformationpurposesonly.

Aftermovingthelogo,thesitedescriptiondoesn’tlooknice,asyoucanseeitfromthefollowingimage:

Wecanchangethat,too.Inordertochangethedefaultlook,wehavetousethesite-descriptionclassprovidedbytheunderscorestheme,andwiththiscode:

.site-description{

font:40024px/1.3'OleoScript',Helvetica,sans-serif;

color:#2B2B2B;

text-shadow:2px2px0pxrgba(0,0,0,0.1);

}

Aswecanseerightnow,IhaveaddedthenewOleoScriptcustomfont,whichwaswp_enqueuedinthefunctions.phpfile,asfollows:

wp_enqueue_style('topcat-description-font',get_template_directory_uri()

.'/css/oleo-script.css');

Hereisthefinallookoftheheaderwithallourchanges:

TheTsizeofthefontinthecontentalsodoesn’tseemgood,sowecanmakeitabitsmallerinthetypographysection:

body,

button,

input,

select,

textarea{

color:#404040;

font-family:Ubuntu,sans-serif;

font-size:14px;

font-size:1.4rem;

line-height:1.5;

}

Itwilllookalotbetterwithallthechangesthatwearegoingtodolaterinthisbook.

ImplementingchangestotheposttemplateWejustmadesomenicechangestotheheader,andnowwewillmakechangestocontent-sidebar.css,too.

ThePostedonandfollowinglinesarerightupagainstthegreybackground,asyoucanseeitinthefollowingimage:

Inthecontent-sidebar.cssfile,Ihaveaddedpadding:30px;tothe@mediaonlyscreenand(min-width:769px)desktopmediaquery,andnowitlooksalittlebitbetter:

NoteThesilvercolorontheleft-handsideofthelogoisthesilverbackgroundthatwejustputinordertoseethedifference.

Nowit’stimetochangeourposttitleandmetatags.Hereisthecurrentlook:

NotethatIhaveintentionallytakenascreenshotofthepartofthelogoandthemenuinordertoshowyouhowsmalltheentrytitleis.Inordertomakeitbiggerandmatchourdesign,wehavetoaddthiscodetothetypographysectionofthestyle.cssfile:

.entry-title{

color:#0480B5;

font-size:2.8rem;

font-size:28px;

text-transform:uppercase;

font-family:'OpenSans',sans-serif;

}

Here,weusedthecolorblueascolor:#0480b5;andthenwehavemadeourfontsbiggerbyusingthefont-size:28px;code.Afterthis,wecapitalizedourfontswithtext-transform:uppercase;,andfinally,wemadesureourOpenSansfontswereusedinfont-family:'OpenSans',sans-serif;.

Wealsowanttochangehowthetitlelooksinnormal,visited,hovered,andactivestatesbecauseourtitleisalsoalink.Thisrequiresaddingthefollowingcode:

.entry-titlea,

.entry-titlea:visited,

.entry-titlea:hover,

.entry-titlea:active{

text-decoration:none;

color:#0480B5;

}

Inthispartofthecode,wemakesurethatourtitle(whichisalinktoo)looksthesameinnormal,visited,hovered,andactivestates.Hereisthelookafterthechange:

Stylingpost’smetadataOurnextstepistostylethemetadataofthepost(Postedon…).Thisdataisinthecontent-single.phptopcat_posted_on()function.Ifwegotothefunction’sdeclaration,wecanseeallthecodethere.Let’smakesomechangesinordertomakethemetaboxlooksbetterandhavemoreinformation.Fromtheoriginalfunction,keepthe$posted_onand$bylinedeclarationsandgetthecategoriesandtheeditbuttonfromtopcat_entry_footerfunction.Thisisbecauseinafooter,wewillonlyhavetodisplaytags.

Hereisthecodeforthetopcat_posted_on()function:

functiontopcat_posted_on(){

$time_string='<timeclass="entry-datepublishedupdated"

datetime="%1$s">%2$s</time>';

if(get_the_time('U')!==get_the_modified_time('U')){

$time_string='<timeclass="entry-datepublished"

datetime="%1$s">%2$s</time><timeclass="updated"

datetime="%3$s">%4$s</time>';

}

$time_string=sprintf($time_string,esc_attr(get_the_date('c')

),esc_html(get_the_date()),esc_attr(get_the_modified_date('c')

),esc_html(get_the_modified_date()));

$posted_on=sprintf(_x('%s','postdate','topcat'),'<iclass="fafa-

calendar"></i>&nbsp;&nbsp;<ahref="'.esc_url(get_permalink()).'"

rel="bookmark">'.$time_string.'</a>');

$byline=sprintf(_x('<iclass="fafa-user"></i>&nbsp;&nbsp;'.'by:%s',

'postauthor','topcat'),'<spanclass="authorvcard"><aclass="urlfnn"

href="'.esc_url(get_author_posts_url(get_the_author_meta('ID'))).

'">'.esc_html(get_the_author()).'</a></span>');

if('post'==get_post_type()){echo'<spanclass="posted-on">'.

$posted_on.'</span>|&nbsp;&nbsp;<spanclass="byline">'.$byline.

'</span>|&nbsp;&nbsp;';

/*translators:usedbetweenlistitems,thereisaspaceafterthe

comma*/

$categories_list=get_the_category_list(__(',','topcat'));

if($categories_list&&topcat_categorized_blog()){

echo'<iclass="fafa-th-list"></i>&nbsp;&nbsp;<span

class="byline">'.__('Category:','topcat').'</span>'.'<span

class="cat-links">'.$categories_list.'</span>';

}

echoedit_post_link(__('Edit',topcat),'|&nbsp;&nbsp;<i

class="fafa-pencil-square-o"></i>&nbsp;&nbsp;<spanclass="edit">',

'</span>');}

}

Let’sanalyzetheimprovementswemade:

1. WehavefirstanalyzedthePHPandHTMLcode,andlateron,wehaveanalyzedthe

CSSattachedtothiscode.Inthebeginning,weprocessedthedate/timecodethatisdisplayedonthepostedonsection.

2. Then,wehavedeclaredthe$posted_onvariable.WetookoffthePostedonwords,asthereisnopointinhavingthemthere.<iclass="fafa-calendar"></i>isthecodewhereweusefontawesomeicons,andinthiscase,weusedacalendaricon.

3. Afterthe$posted_onvariable,wehavea$bylinedeclaration,andhere,weprintedtheauthorinformationtogetheragainwith<iclass="fafa-user">,whichisafontawesomeiconfortheuser.

4. Inthethirdsection,weoutputtedcategories;beforedoingthis,wehadtocheckwhetherourpostisatypepost.Ifitisatypepost,thenwegetacategoryoralistofcategoriesthatareassignedtothispostwithget_the_category_list().

5. Afterthis,wehavecheckedwhetherthelisthasreturnedcategoriesandwhethertheposthasmorethanonecategorywithtopcat_categorized_blog().Iftheposthasoneormorecategoriesassociatedwithit,weprintthemout,againwith<iclass="fafa-th-list">,whichisafontawesomeiconforalist,andI’veseenitasapropericonforthecategories.

TipNotethatyoucanputiconsofyourchoiceforthis;although,again,Iwillrecommendthatyoufollowthebookandmakeyourchangeslateron.

Attheendofthefunction,wehaveacodefortheeditpostlinkwith<iclass="fafa-pencil-square-o">,whichisafontawesomeiconforediting.Now,wearegoingtomakesomeCSSchanges.

SincewehavealreadyanalyzedthemarkupandPHPcode,let’sseewhatwedidwithCSSinordertoaccomplishournewlook.Asthepost’smetahasitsowncontainer,<divclass="entry-meta">,wehaveediteditfirstinstyle.cssfile,andeditedcodeisinthepostsandpagessection:

.entry-meta,.tags-links{

background:nonerepeatscroll00#F8F8F8;;

border-radius:3px;

margin:12px024px;

overflow:hidden;

padding:5px12px;

}

.entry-metaspan{

font-size:13px;;

font-size:1.3rem;

margin:06px00;

padding:0;

}

Here,wehavefirstdefinedasilverbackgroundbyusingbackground:nonerepeatscroll00#F8F8F8;,border-radius,margin,overflow,andpadding.Then,forthe

child-elementspan,wehavedefinedafontsizemarginandpadding.Afterthis,wehavedefinedthestylesforentrymetalinks,theauthor,andcategorylinks,aswellasthetagsthatwehaveusedinthefooterofthepost(wewillcoverthislater):

.entry-metaa,

.entry-metaa:visited,

.entry-metaa:hover,

.entry-metaa:active

.authora,

.cat-links,

.tags-linksa,

.tags-linksa:visited

.tags-linksa:hover,

.tags-linksa:active

{

color:#000;

line-height:2.8;

text-decoration:none;

}

Then,wehavethe.bylineand.tag-linksclassestosetthedefaultcolorassilver:

.byline,.tags-links{color:#999;}

Asthelaststep,wewillcolorourfontawesomeiconsinblue:

.fa-calendar,.fa-user,.fa-th-list,.fa-pencil-square-o,.fa-tag{color:

#0480B5;}

Afterthechanges,thisishowitalllooks:

Itlooksprettygoodnow,right?

ContentsectionItdoesn’tlooknicehowthecontentisseparatedfromthesidebar,asthereisalotofemptyspaceinbetween:

Tofixthis,weshouldchangetherightmargininthe.site-mainclassfrom:

.site-main{

margin:025%00;

}

To:

.site-main{

margin:05%00;

}

The.site-mainclassislocatedincontent-sidebar.css.

Nowthecontentlooksalotbetter,asyoucanseeithere:

Aswecanseefromthepreviousimage,thelinkinthecontentpost_class()functiondoesn’tlookappealingatall(justadefaultvisitedlinkcolor),andwecanchangethiswithonlyasimplecodeinstyle.css:

.entry-contenta,

.entry-contenta:visited

.entry-contenta:hover,

.entry-contenta:active

{

color:#0480B5;

line-height:1.6;

text-decoration:none;

}

Hereiswhatitlookslikeafterourchanges:

Thepost_class()linkisinourbluecolornowandit’snotunderlined.

Now,ifwejustgobacktotheindexpagebyclickingontheHomelinkinthemenuandthengotothepostwiththenameMarkup:HTMLTagsandFormatting,wewillseemoreHTMLelementsthatwecanstyle.

Tip

Thispostandalltheotherposts/contentinourprojectdon’tcomewithWordPressbydefault.WehaveloadedthembyimportingtheThemeUnitTestDatafromhttp://codex.wordpress.org/Theme_Unit_Test.

Wewillcoveronlysomeofthemhere,astherearesomanyofthem.Thisisthelookofourcurrentheadings:

Ifwegotothetypography(2.0)sectionofstyle.css,wewillbeabletoseesomeheadingswehavealreadydefined:

h1,

h2,

h3,

h4,

h5,

h6{

clear:both;

font-family:'OpenSans';

font-weight:800;

color:#0480B5;

}

Weshouldchangethecolortoourblue(color:#0480B5;)tomakeeverythingthesame,thenwecanstylealltheheadingsizesseparately:

h1{

font-size:28px;

font-size:2.8rem;

}

h2{

font-size:24px;

font-size:2.4rem;

}

h3{

font-size:20px;

font-size:2.0rem;

}

h4{

font-size:18px;

font-size:1.8rem;

}

h5{

font-size:16px;

font-size:1.6rem;

}

h6{

font-size:14px;

font-size:1.4rem;

}

Hereisthenewlookofourheadings:

Underheadings,wehaveaBlockquotethatlooksprettybasic:

Sohere,wewillfirstdefinemarginandpaddingandalsoaddthedottedborderatthetopandbottomoftheblockquote:

blockquote{

margin:1.5rem1.5rem;;

border-top:dotted1px#999;

border-bottom:dotted1px#999;

padding:1em;

}

Afterthis,wewillstyletheptagnestedinblockquote:

blockquotep{

font-style:italic;

margin-bottom:auto;

}

We’vemadethefontsitalic,andsincethepelementhassomestrangemarginbottom,wehavedonearesetitherewithmargin-bottom:auto;.

Wealsowanttomaketheauthorinthecitetagmorevisible;wecandothiswith:

cite{

font-weight:600;

}

Sincethecitationisnotnestedinblockquotebutinthenextptag,wewouldliketoalignittotheright:

blockquote+p{

width:100%;

text-align:right;

}

Hereisthelookafterallthesechanges:

NoteThereareanumberofHTMLtagstostylehere,andsincewehavecoveredthebasicsandbecauseitwilltakealotoftimetocoverthemall,wearegoingtomovetothenextpart,thatis,tags.

TagsWehavedecidedtodisplaytagsinaboxjustafterthecontent.

Inthelastpartofthischapter,wearegoingtoworkonnavigationinposttemplates,andthecodeforthisislocatedinthetopcat_entry_footer()function,whichisalsolocatedinthetemplate-tags.phpfile.

TipTopcat_entry_footer()isthefunctionthathandlesthefooterforasinglepost,notawebsitefooter.

Ihavechangedthetagfunctionalitywithmyownsolutioninthetopcat_entry_footer()functionofthetemplate-tags.phpfile,anditlookslikethis:

if('post'==get_post_type()){

$posttags=get_the_tags();

echo'<divclass="tags-links">Tags:<span>&nbsp;&nbsp;';

if($posttags){

foreach($posttagsas$tag){

echo'<iclass="fafa-tag"></i>&nbsp;&nbsp'.

'<ahref="'.get_tag_link($tag->term_id).'">'.

$tag->name.'</a>&nbsp;&nbsp';

}

}

echo'</span><div>';

}

Atfirst,wehavecheckedwhetherthepageisoftypepost,andthen,wehaveloadedthetagsinthe$posttagsvariablewiththeget_the_tags()function.Afterthis,weareloopingtroughthetagswiththeforeachloopasforeach($posttagsas$tag),andinfrontofeverytag,wehavedisplayedafontawesometagiconwiththe<iclass="fafa-tag"></i>markup.

The.tags-linkssectionhasthesamestylesasthatof.entry-meta:

.entry-meta,.tags-links{

background:nonerepeatscroll00#f8f8f8;

border-radius:3px;

margin:12px024px;

overflow:hidden;

padding:5px12px;

}

Wearealsostylingthelinksinsidethe.tags-linkssectionwiththesamestylesasthestylesfor.entry-metalinks:

.entry-metaa,

.entry-metaa:visited,

.entry-metaa:hover,

.entry-metaa:active

.authora,

.cat-links,

.tags-linksa,

.tags-linksa:visited

.tags-linksa:hover,

.tags-linksa:active

{

color:#000;

line-height:2.8;

text-decoration:none;

}

Finally,wewillcolor.tags-linkswiththesamemarkupasthatof.byline:

.byline,.tags-links{color:#999;}

HereisthefinallookoftheTags:section:

PostnavigationAsIhavesaidpreviously,thefinalpartinthischapterispostnavigationorprevious/nextnavigation.Ifwegotothesingle.phpfileandtopcat_post_nav()functioncall,wewillseethisisthecalltopostnavigation.Thisfunctionispartofunderscoresthemeandit’sdeclaredinthetemplate-tags.phpfile:

Aswecansee,itlooksprettybasic,butwearegoingtoimproveit.HereisthechangedPHPcode:

Let’sanalyzethechangedcode:

Thefirstpartofthecodewaschangedintheprevious_post_link()function,whereIaddedafontawesomemarkup,namely<iclass="fafa-arrow-leftfa-3">fortheleftarrow.Lateron,wehavechangedthewordsfromthePreviouspostlinktoPreviousandaddeda<br/>tagafterit.Wehavealsoappliedthesamechangestoprevious_post_link(),too.

NoteNotethatIdidn’tchangeanyCSSclasses.

Afterthis,allotherchangesthatwearegoingtodoareinstyles.cssfile.

Firstly,wewilladd.fa-arrow-leftand.fa-arrow-righttothelinewhereallfontawesomeiconsarebeingcoloredinourbluecolor:

.fa-calendar,.fa-user,.fa-th-list,.fa-pencil-square-o,.fa-tag,.fa-

arrow-left,.fa-arrow-right{color:#0480B5;}

Becausethesearrowiconsarereallysmall,wearegoingtomakethembiggerwiththiscode:

.fa-3

{

font-size:26px!important;

font-size:2.6rem!important;

}

NoteNotethatIhaveaddeda.fa-3classinthefontawesomemarkup.

Afterthis,weneedtomakeallthefontsinthe.nav-previousand.nav-nextsectionsblackanditalicrespectively.Wearedoingthisbecausethetitlesofthenextandpreviousblogpostsneedtobeinthisspecificstyleinordertobeidentifiable:

.nav-previous,

.nav-next,

.nav-previousa,

.nav-nexta,

.nav-previousa:visited,

.nav-previousa:hover,

.nav-previousa:active,

.nav-nexta:visited,

.nav-nexta:hover,

.nav-nexta:active

{

color:#000;

font-style:italic;

}

Then,weneedtostyletheNextandPrevwords:

.meta-nav,

.meta-nava,

.meta-nava:visited,

.meta-nava:hover,

.meta-nava:active

{

color:#0480b5;

font-family:"OpenSans",sans-serif;

font-size:26px;;

font-size:2.6rem!important;

line-height:26px;

text-transform:uppercase;

font-weight:800;

padding:10px;

font-style:normal;

}

Aswecanseeintheprecedingcode,we’vecoloredthewordsinblue;then,wehaveassignedtothemaproperfontandfontsize,andmuchmore.

NoteWehaveusedfont-style:normalbecauseofthepreviousdeclarationwhereweusedfont-style:italic.

Finally,withthefollowingcode,wearemakingsurethatnoneofourlinksinthissection

areunderlined:

.nav-linksa,

.nav-linksa:visited

.nav-linksa:hover,

.nav-linksa:active

{

text-decoration:none;

}

Hereisthefinallookofourwork:

SummaryInthischapter,wehavefocusedonasingleblogpostpage—startingfromthetop,workingdownthroughtitleandmeta,thenthecontent’sHTMLtags,andeventuallytothefooterofasinglepost.Toaccomplishallthesechanges,wehaveworkedwiththesingle.php,content-single.php,template-tags.php,styles.css,functions.php,andheader.phpfiles.

Inthenextchapter,wewillworkontheitemsthatappearinthesidebar(widgets),andwewillchangethewaycommentsappearinposts.

Chapter6.ResponsiveWidgets,Footer,andCommentsAswearegoingtocoveralotofthingsinthischapter,wewillbreakitintotwosections.Thisway,itwillbemuchmoreinterestingandeasierforyoutounderstand.But,don’tworry;itwillbealotoffun,andatthesametime,youwilllearnalotaboutwidgets,thefooter,andcomments.

Withoutwastinganytime,let’sseewhatwewillcoverinthischapter.

Inthefirstsection,wewill:

LearnmoreaboutwidgetsLearnhowtocustomizethesewidgetsLearnmoreaboutsidebarsandhowtostylethemLearnhowtoeditthefooterLearnhowtomakeourwidgetsresponsive

Inthesecondsection,wewill:

Learnmoreaboutcommentsandhowtocustomizethem

WidgetsWidgetsaresmallsectionsorcontainersthatprovidesometypeoffunctionalitytoourwebsite.Basically,widgetsgetdeployedintosidebars,whichwearegoingtoexamineinjustamoment.WordPressprovidesanumberofwidgetsbydefault,andmanypluginsdefineadditionalwidgets;eventhemescandefinewidgets.Widgetscanbe,forexample,listsoftags,categories,latestposts,contactforms,orTwittertimelines.

Aswecansee,theycanbealmostanything.Whenwecreatewidgetsinacode,theyappearintheWidgetssectionunderAppearance,wherewecanselectthewidgetthatwelike.Wecanalsoaddittoanysidebarthatwewant,asasinglethemecanhaveanumberofsidebars.

Inthepreviousimage,wehavefirstchosenacalendarwidget,(#1)andthendecidedtoaddittothesidebarbyclickingontheAddWidgetoption(#2).Withthis,thecalendarwidgetwillbeaddedtothesidebar(#3).Insteadofdoingitthisway,wecansimplydraganddropthewidgetonthesidebar.Assoonasweaddthewidgettothesidebar,wehavetheoptiontocustomizeit,too:

NoteSincewidgetsareseparateprograms/features,theoptionsavailabletocustomizethewidgetsdependonthecodethatcreatesthewidget.

Inthiscase,asseenintheprecedingimage,wehavetheoptiontoaddthetitle.

NoteSomewidgetsmaynothavetheoptiontobecustomized.

SidebarsSidebarsareareasthatareactuallycontainersforourwidgets.Afewyearsago,whentheywerefirstbuilt,theywereusedfortheleftandrightsidebars;that’swhytheyhavethisname.Sidebarcontainershaveevolvedsomuch,andnowtheycanbeplacedanywhereyouwantthemtobe:ontheleftorrightside,intheheaderorfooter,andeveninthepostcontentarea.Sidebarcontainersareusuallydefinedinthefunctions.phpfileusingtheregister_sidebar()function,andthisisalsothecaseinourexample:

NoteMoreinformationabouttheregister_sidebar()functioncanbefoundinChapter10,SubmittingYourThemetoWordPress.orgofourbookorinit’sCodexpageathttp://codex.wordpress.org/Function_Reference/register_sidebar.

Aswecanseefromtheprecedingimage,wehaveafunctioncalltotopcat_widgets_init(),whichislateroncalledwiththeadd_action('widgets_init','topcat_widgets_init');hook.Thismeansthatthisfunctionisbeingtriggeredwiththewidget_initfunction.Aswecanalsoseefromtheprecedingcode,intheregister_sidebar()function,wearesettingthefollowing:

name

id

description(whichiscurrentlyempty)before_widgetandafter_widget(whereourwidgetsaregoingtobenestedin,forexample,the<aside>tag)before-titleandafter-title(whereourtitleisgoingtobenested)

Since,forourtheme,wewanttohavemorethanonesidebar,wewillcreateanotherone(thefootersidebar)inthesamefunction,justunderthefirstregister_sidebar()code:

Aswecanseeinthepreviousimage,wejustneedtoaddadifferenttitle,ID,andadescription.Now,wecanseeournewwidgetareabynavigatingtoAppearance|Widgets:

Intheprecedingimage,wecanseethatournewsidebar,thefootersidebar,hasbeenaddedbesidetheoldsidebar.Underneathit,ournewdescriptionFooterwidgetsgoherehasbeenadded,too.

NoteWehavetoclickonthearrowinthetop-rightcornerfortheareatoexpandsowecanseethenewdescription.

Inordertoseeoursidebarsonthelivewebsite,wehavetocompletethefollowingtwosteps:

Declarethesidebar(usuallyinsidebar.php)Callthedynamic_sidebar()functioninordertodisplaythesidebarinourtheme

NoteMoreinformationaboutthedynamic_sidebar()functioncanbefoundinChapter10,SubmittingYourThemetoWordPress.orgofourbookorinit’sCodexpageathttp://codex.wordpress.org/Function_Reference/dynamic_sidebar.

Sinceweareusingtheunderscorestheme,thesidebardeclarationcodeisprovided

insidebar.php:

Aswecanseefromtheprecedingscreenshot,wearecheckingwhetherthesidebarwiththeIDsidebar-1haswidgetsinit.Ifithas,theresultwillreturntrue,andifitdoesn’t,itwillreturnfalse.Iftheresultistrue,ourcodewillproceedtothenextsectionwherethesidebarwillbeloadedwithdynamic_sidebar('sidebar-1');.Sincewecurrentlyhaveanumberofwidgetsloadedinthedefaultsidebar,ifwegotoAppearance|Widgets,wewillseethefollowing:

Thesewidgetsarealsoloadedonourhomepageinthesameorder:

Whydoweseethissidebar?Weseeitbecauseitwascalledintheindex.php,page.php,search.php,andsingle.phparchivetemplateswiththeget_sidebar();functioncall.

Note

Inordertomakeeverythingclear,weneedtoincludethesidebar.phpfilewiththeget_sidebar()function.Ontheotherside,thedynamic_sidebar()functionisactuallyresponsiblefordisplayingthesidebar.

Inourcase,wearegoingtouseonemoresidebarinthefooter,sidebar-footer.Weneedtosavethesidebar.phpcopyasanewfilewiththenamesidebar-footer.php,whichwearegoingtoeditforoursidebarfooterpurpose.Hereisthelookofoursidebar-footer.phpfile:

<!--Customsidebarcodebegin-->

<?php

if(!is_active_sidebar('sidebar-footer')){

return;

}

?>

<divid="secondary"class="widget-area"role="complementary">

<?phpdynamic_sidebar('sidebar-footer');?>

</div><!--#secondary-->

<!--Customsidebarcodeend-->

NoteNotethatwehavechangedthevaluesfromsidebar-1tosidebar-footer.

Inordertoseethisfileinthefooter,weneedtomakethecallwithget_sidebar('footer');.

NoteNotethe'footer'name.Ifwecallourfootersidebarfile,namelysidebar-dejan.php,thenourcallshouldbeget_sidebar(dejan');.Isn’tthatawesome?

Butwait!Westillcan’tseeanychanges.Doyouknowwhy?

ItisbecauseweneedtogotoApperance|Widgetsfirst,andaddatleastonewidgettothearchiveswithatitle,inourcaseArchivesfooter,asyoucanseeitinthenextscreenshot:

Now,ifwescrolltothebottomofourindexpageorjustgotoanysinglepost,wewillbeabletoseeourarchivesfooterwidget,asshowninthefollowingpicture:

StylingsidebarsNowthatwehavecreatednewwidgetareaandareabletoaddwidgets,weshouldgoandstylethesidebars.Todothis,weneedtousethemonsterwidgetthatweinstalledinChapter1,ResponsiveWebDesignwithWordPress.ThemonsterwidgetcontainsallthedefaultwidgetsthatcomewithWordPress.Itisagreatadditiontoourtoolboxaswiththis,wedon’tneedtoloadthewidgetsonebyone.Whenweloadthewidgets,westylethemwithourcodeinordertomakesurethatourthemeis100percentcompatiblewiththem.Whatdoes“compatible”mean?

Itmeansthatiftheenduserputsanyormultiplewidgetsinoursidebar,theyshouldnotbreakthelayoutofthepagenorthewidgets’ownthelayout.

Beforewestartmakingbigchanges,weneedtodifferentiatetherightsidebarfromthecontent,andwecandothisbysimplyaddingthislineto.widget-areaincontent-sidebar.css:

background:nonerepeatscroll00#f8f8f8;

Hereisthenewlookoftherightsidebar:

Aswecanseefromtheprecedingscreenshot,wehaveadarksilverline,whichisourbackgroundcolor,ontheright.Then,wehaveoursidebarinlightsilvercolor,followedbyourcontentinwhite.

Ifwegotoourcodeinthefunctions.phpfile,wherewedefinedthesidebararea,wewillseethefollowing:

register_sidebar(array(

'name'=>__('Sidebar','topcat'),

'id'=>'sidebar-1',

'description'=>'',

'before_widget'=>'<asideid="%1$s"class="widget%2$s">',

'after_widget'=>'</aside>',

'before_title'=>'<h1class="widget-title">',

'after_title'=>'</h1>',

));

Aswecansee,ourwidgetswillbecontainedin<asideid="%1$s"class="widget%2$s">withtheclassnamenamedwidget.AsIdon’tlikethecurrentpaddingforthisclass,wewilladdpadding:30px10px.Thewidgetclassislocatedinthewidgetsareainstyless.css.

Hereisthelookwehadbeforethechange:

Hereisthenewlook,afterthechange:

Widgettitlefontsaretoobig,sowewilladdthisstyletostyle.css:

.widget-title

{

font-size:1.7em;

}

Wealsoneedtodifferentiatewidget’stitlefromthecontent,andwewilldothisbyaddingtheensuingcodetothewidget-titleclass:

border-bottom:1pxdashed#666;

margin:10px0px;

Nowwecanscrolldownthroughthepagetoseethechanges.Theonlythingsthatdon’tlookparticularlyinterestingarethelinksandunstyledlists:

NoteIhavefirsttriedtocolorourlinksinblue(#0480b5),buttheydidn’tlookappealingasourtitleisofthesamecolor,meaningtherewastoomuchofblueeverywhere.Ihavetestednumerouscolors(andyoushoulddothesametoo).

Finally,Icameupwiththissolutionthatwillworkbestforourlinks:

.widgeta,

.widgeta:visited,

.widgeta:hover

.widgeta:active,

#today

{

color:#666;

line-height:1.6;

text-decoration:none;

font-weight:500;

}

.widgeta:hover{

text-decoration:underline;

}

Here,wehavesetallthelinksinsilvercolorandwithaproperlineheight.Afterthis,wemadesurethatallthelinks,excepthoverlinks,arenotdecorated,asshowninthefollowingimage:

Finally,weputafontweightof500todistinguishlinksfromnormalfonts(forexample,inthecalendarwidget.)

NoteInthecalendarwidget,wehaveaspecialIDforthecurrentday(#today),whichIhaveusedtostylethatnumbertoo.

Now,let’saddthosestylesinordertoeditlists:

.widgetul,.widgetli{

list-style:none;

margin:0.3em00;

}

.widgetlili{margin-left:1em;}

Aswecanseeintheprecedingcode,wehavedisabledthewidthofliststylesandthenaddedamargintopof0.3em.Finally,weaddedmargin-leftof1emforchildlists.

Let’sseethelookofliststhathavechildren:

EditingthefooterOurnextstepistoeditthefooter.

First,weneedtomakeourfooterdistinctive,andwecandothisbychangingthebackgroundcolorofthe.site-footerclassinthecontent-sidebar.phpfile:

background:nonerepeatscroll00#2f3336;

Now,wearegoingtocreateafootersectioninthestyle.cssfile.Sincewehavejustchangedthebackgroundcolorofthefooter,weneedtochangethewidgettitletoo:

.site-footer.widget-title

{

font-size:1.7em;

border-bottom:1pxdashed#ccc;

margin:10px0px;

color:#fff;

}

Here,wehavechangedthetitlecolortowhiteandthebottombordercolortosilver:

Somelinksandcontentarealmostunreadable,ascanbeseeninthefollowingimage:

Wecansolvethisproblemwiththefollowingcode:

.site-footer.widgeta,

.site-footer.widgeta:visited,

.site-footer.widgeta:hover

.site-footer.widgeta:active,

#today

{

color:#999;

line-height:1.6;

text-decoration:none;

font-weight:500;

}

Withtheprecedingcode,wearemakingallthewidgetlinksinthefootertobeofamediumdarksilvercolor:

Nowit’smorereadable,butwestillneedtofixsomeparts,right?Thatnumberinthebracketsisalmostinvisible:

.site-footer.widgetulli

{

color:#666;

}

Theprecedingcodesolvestheproblemaswithit,wehaveaddedadarkershadeofsilversowecoulddistinguishthelinkfromthenumber.

Wefixedthevisibilityissueforanumberofwidgets,butthecalendarwidgetisstillunfinished:

Thislineofcodewillsolvetheproblemforalltheunfinishedwidgets:

.site-footerp,.site-footerstrong,.site-footertd,.site-footerth,

.site-footercaption

{

color:#999;

}

Nowlet’shavealookattheresult:

Theonlymissingpartisstylingforthecurrentday,andwecansolvethiswiththefollowinglineofcode:

.site-footer#today{

color:#fff;

font-weight:600;

}

Hereisthelookafterourchange:

Now,asourfooterandwidgetslookfine,weshouldhavethemrenderedsidebysideforadesktoplookinsteadofhavingthemoneaboveanother:

Inordertodothis,wejustneedtoaddthiscode:

.site-footer.widget{

float:left;

width:30%;

margin:01rem2rem2rem;

}

Intheprecedingcode,we’vefirstmadeallthewidgetsfloattotheleftsotheycouldberenderedonebesidetheother.Afterthis,wegavethewidgetsawidthof30percentsowecanhavethreewidgetsinonerow.Finally,wesetthemarginsto0,1rem,2rem,and2rem(top,right,bottom,andleft).

Thefinalstepwithwidgetsistomakethemfluid;thatis,ifweresizethebrowserrightnow,forexampletothemobilesize,thewidgetswillstillbeonebesidetheotherinsteadofoneabovetheother:

NoteWehaveusedapercentagewidthinordertomakeourlayoutfluid(partofaresponsivelayout)butwehaven’tyetappliedthebreakpoints.Whenweapplythebreakpoints,thefooterwillbecomeresponsive(itwillrespondtodifferentsizesofthescreen).

Inordertomakeourwidgetsresponsiveinthefooter,wearegoingtousethemasonry.jslibrary.

NoteMasonryisagreatJavaScriptgridlibrarythatoptimizesthelayoutbasedontheverticalspacesize.Inourcase,itcanresizeourwidgetsdependingonthelayoutwidth.Formoreinformationaboutmasonry,visithttp://masonry.desandro.com/.

ThegoodthingaboutmasonryisthatitalreadyexistsinWordPress.Wejustneedtoloaditinourfunctions.phpfilewhereweareloadingalltheother.jsfiles:

wp_enqueue_script('topcat-masonry','/js/masonry_custom.js',

array('masonry'),false,false);

Intheprecedingcode,wehavecalledourcustommasonryfilewherewearegoingtosetthedefaultvaluesformasonry.Aswecanseefromthecode,wesetmasonryasadependencywitharray('masonry').Thisway,weareloadingmasonryfirstandthenourcustommasonrycode.

Nowisthetimetocreatethemasonry_custom.jsfileinourthemesjsfolder.

Afterthis,weshouldwirethemasonrytothefooterwidgetsinourmasonry_custom.jsfilewiththiscode:

jQuery(document).ready(function($){

var$container=$('#sidebar-footer');

$container.masonry({

itemSelector:'.widget',

columnWidth:'.widget',

isFitWidth:true,

isAnimated:true

});

});

Here,wehavesetacontainerto#sidebar-footerandthenitemSelectorto.widget,obviously.TheinterestingpartaboutmasonryisthatyoucansetacolumnwidthtoaCSSclassinsteadofanumber,andthischangemakesitevenmoreresponsive.Trybothonyourown,thenumber(forexample,300forcolumnWidth)andCSSclass(.widgetforcolumnWidth),andcomparetheresults.

Inthesidebar-footerfile,weshouldmakesurethatourwidgetcontainerhasthesidebar-footerID:

<divid="sidebar-footer"class="widget-area"role="complementary">

<?phpdynamic_sidebar('sidebar-footer');?>

</div>

Finally,whenweresizethepage,thewidgetswillloadnicely(onebesidetheother):

However,ifweminimizethescreentoomuch,thelayoutwillbreak.

Inordertofixthis,wehavetocustomizeourmasonrycustomcodeinasimilarwayaswedidwithsuperfish.js:

varphoneSize=600;

jQuery(document).ready(function($){

var$container=$('#sidebar-footer');

if($(document).width()>=phoneSize){

$container.masonry({

columnWidth:'.widget',

isFitWidth:true,

isAnimated:true,

itemSelector:'.widget'

});

}

$(window).resize(function(){

if($(document).width()>=phoneSize){

$container.masonry({

columnWidth:'.widget',

isFitWidth:true,

isAnimated:true,

itemSelector:'.widget'

});

}

//<phoneSizedisablemasonry

elseif($(document).width()<phoneSize){

$container.masonry({

columnWidth:'.widget',

isFitWidth:true,

isAnimated:true,

itemSelector:'.widget'

});

$container.masonry('destroy');

}

});

});

Here,wehavesetthephonesizevariableto480,whichis,actually,thesamesizeasthatofcontent-sidebar.cssforamediaquery.Afterthis,ineachsection(case),weinitializedmasonrywithitsdefaultvalues.Forscreensizeslessthanthephonesize,wedisabledmasonryandhadourwidgetsdisplayedoneperline.Forthis,weusedtheCSSplacedin@mediascreenand(max-width:480px)instyle.css:

#sidebar-footer{width:100%!important;}

#sidebar-footer.widget{

width:100%;

float:none;

}

Whenweresizethescreentothephonesize,wegetonlyonewidgetperline:

WorkingwithcommentsInthissection,wearegoingtotalkabout:

ThepurposeofcommentsandwhytheyareimportantStylingcommentstitleStylingcommentsthemselves,includingtheauthorcommentsStylingcommentsnavigation

Thecommentsfeatureisaveryimportantpartofanywebsiteasthecommentsenableinteractionbetweenthesiteownerandvisitors.Atthesametime,theybringmorevaluetothesite,asmoreinformationisprovidedandthesitecanhavemoretrafficaspeoplewhofolloworrespondtocommentscancomeback.AsWordPresshastwotypesofpages,thatis,thepageandthepost(includingcustomposts),thecommentscanbedisplayedonboth.

TipIrecommendthatyoudisablecommentsonpagesofthetype“page”onbusinesswebsites.Idon’tseethepurposeofvisitorsleavingcommentsonour“contactus”pageorthe“aboutus”page,right?

Inordertodealwithcommentsinourtheme,weshouldgotoTemplate:Comments,whichcanbefoundbyusingthesearchwidgetwiththekeywordTemplate:Comments,orinwpadminbygoingtothepostssection,searchingforthesamekeyword,andthenchoosingthePreviewoption.Whenwefinallygotothatpost,wewillseealotofcommentsthere.Sincewedon’tneedtodealwiththatmany,wecangotoSettings|Discussion|Breakcommentsintopagesandtypethenumber5.

NoteMakesurethatthisoptionischecked;then,savethechanges.

Nowweareabletoseethenumberofcomments:thecommentstitle(#1),commentstoolbar(#2),andcommentsthemselves(#3):

Youareprobablywonderinghowthecommentsareloaded,right?

Ifwegotosingle.php,wewillseethefollowingcodearoundline19:

<?php

//Ifcommentsareopenorwehaveatleastonecomment,loadupthe

commenttemplate

if(comments_open()||get_comments_number()):

comments_template();

endif;

?>

Aswecansee,thiscodeischeckingwhethercommentsareenabledandifthereareanycomments.Iftheanswerisyestoboth,wecallthecomment_template()function,whichloadsthecomments.phpfile.Sincecomments.phphasalotofcode,Ihavecreatedacopyofitcalledcomments_old.php.

NoteWearegoingtomakeanumberofchangestothecomments.phpfile,andinordertoavoidtheconfusion,Iwilluselinenumbersasreferences.

StylingcommentstitleBeforewedoanythingelse,weshouldchangethewordsaroundline28,fromthoughttocommentandfromthoughtstocomments:

Thisisthecodebeforethechange:

printf(_nx('Onethoughton&ldquo;%2$s&rdquo;','%1$sthoughtson

&ldquo;%2$s&rdquo;',get_comments_number(),'commentstitle','topcat'),

number_format_i18n(get_comments_number()),'<span>'.get_the_title()

.'</span>');

Thisisthecodeafterthechange:

printf(_nx('Onecommenton&ldquo;%2$s&rdquo;','%1$scommentson

&ldquo;%2$s&rdquo;',get_comments_number(),'commentstitle','topcat'),

number_format_i18n(get_comments_number()),'<span>'.get_the_title()

.'</span>'););

Asyoucanseenow,inthecodebetweenlines33through39andagainbetween50through56,wehaveacommentsheader.Wereallydon’tneedboth,solet’sdeletetheoneonlines33through39.Sincewehavedeletedthefirstcommentsheader,wenowhavethiscode:

<olclass="comment-list">

<?php

wp_list_comments(array(

'style'=>'ol',

'short_ping'=>true,

));

?>

</ol><!--.comment-list-->

Intheprecedingcode,wehavethecommentlistclassandthenthefunctioncalltowp_list_comments(),whichactuallydisplaysthecomments.

StylingcommentsNow,let’schangethestylingofourcomments.Instyles.css,commentsarelocatedinthecommentssection:

Aswecanseeintheprecedingimage,wehavetodoalotofchangesinordertomakethislooknice.

Atfirst,wewillfixthelookoflinksbymakingthemblackandunderliningthemonlywhentheyarehoveredover:

.comment-bodya,

.comment-bodya:visited,

.comment-bodya:active

{

text-decoration:none;

color:#000;

}

.comment-bodya:hover

{

text-decoration:underline;

color:#000;

}

Secondly,weshouldhavesomespacebetweentheimageandtheauthor’sname,theauthor’snameandtheword“says”,andthetimestampandtheword“edit”:

.comment-author.fn,.comment-metadata.edit-link

{

margin:0.5em;

}

Afterthis,let’smakethebuttonlinks(editandreply)lookalittlebitdifferentthantheothertextbymakingthembold:

.comment-metadata.edit-link,.reply{

font-weight:600;

}

Then,wemakethecomment’scontenttextitalic:

.comment-content{

font-style:italic;

}

Finally,wemakecommentsdistinctivefromborder-bottom:

.comment-listarticle{

border-bottom:1pxdashed#666;

}

Hereisourimprovedlook:

Itlooksalotbetterthanitdidinthepreviousimage,right?But,ifweresizethebrowsertothemobilesize,thelistinwhichcommentsarelocatedwillgetmoreandmorenested(indented).Toresolvetheproblemwithindentation,addthefollowingcodetothemediaqueryweusedforthesidebarcode,whichislocatedattheendofstyles.css:

/*comentscomments*/

#commentsol.children{

list-style-type:none;

margin-left:0;

padding:0;

}

ul,ol{

margin:001.5em0em;

}

CommentsnavigationThefinalstepistostylethecommentsnavigation:

TipWecanhaveanumberofcommentsonourpage/postif,forexample,ourcontentispopular.Thiswillmakeourpagetoobiganditwilltakealongtimetoload.Tofixthis,wecanusecommentsnavigation,aswiththis,thenumberofcommentscanbelimited;ifourreaderswanttoreadthemall,theycanusethecommentsnavigation.

Atfirst,weshouldtakeouttheword“comments”fromthecodeinfunctions.phparoundthelines45and46:

<divclass="nav-previous"><?phpprevious_comments_link(__(""."<i

class='fafa-arrow-leftfa-2'></i>&nbsp;Older",'topcat'));?></div>

<divclass="nav-next"><?phpnext_comments_link(__("Newer&nbsp;<i

class='fafa-arrow-rightfa-2'></i>"."",'topcat'));?></div>

Inordertomakethelookmoreinformed,weshouldalsoaddfontawesomearrows(fa-arrow-leftandfa-arrow-right).Ascommentsarelessimportantforusthanthecontent,weshouldresizefontawesomeiconswiththe.fa-2class.Let’sanalyzetheCSScodeinstyle.css:

comment-navigation

.comment-navigation,

.comment-navigationa,

.comment-navigationa:visited,

.comment-navigationa:active

{

color:#666;

font-family:"OpenSans",sans-serif;

font-size:20px;

font-size:2.0rem!important;

;

line-height:20;;

text-transform:uppercase;

font-weight:800;

padding:10px;

font-style:normal;

text-decoration:none;

}

Intheprecedingcode,wecoloredlinksinthenavigationwithadarkersilvercolorwithtext-decorationsettonone(meaninglinksarenotunderlined)andfont-sizesetto20px.

.comment-navigationa:hover,.comment-navigationa:hover.fa-arrow-left,

.comment-navigationa:hover.fa-arrow-right

{

font-style:normal;

color:#000;

}

Here,wehavemadethelinksblackwhenhoveredover,andwithfont-style:normal;,wehavemadesurethatwhenhoveredover,fontswillnotbeinitalic.

.fa-3

{

font-size:20px!important;

font-size:2.0rem!important;

;

}

Here,wemadesurethatfontawesomeiconsaresmallerincommentnavigationthaninthecontentpart.

Here,wewillcolorfontawesomeiconstoblack:

.comment-navigation.fa-arrow-left,.comment-navigation.fa-arrow-right

{

color:#666;

}

Let’sseethefinallookofasinglecommentandthecommentnavigationunderit:

SummaryInthischapter,welearnedalotofusefultipsandtricks.Inthefirstsection,welearnedmoreaboutwidgets,howtostylethem,andhowtomakethemresponsive.Then,welearnedmoreaboutsidebars,andfinally,welearnedhowtoeditthefooter.Inthesecondsection,welearnedmoreaboutcommentsandhowtoeditandstylethem.

Ibetyouthinkthatyouknowitallbynow,right?

Well,thebadnewsisthattherearealotofthingsthatwestillhavetolearn;however,thegoodnewsisthatyouarehalfwaydonealready!

Gogetyourcoffeeandcontinueonreading,asinthenextchapter,wewilldiveintothewonderfulworldofimagesandvideos!

Inthenextchapter,wewilllearnhowtodealwithfeaturedimagesandhowtosetupandresizetheseimages,imagecaptions,andimagegalleries.We’llalsolearnhowtomaketheimagegalleriesresponsive.

Chapter7.WorkingwithImagesandVideosInthischapter,wewillstartwithsomethingfunandexplore,somemightsay,themostimportantvisualitemtolookforwhendesigningawebsite.Aswearevisualcreatures,imagesandvideosarecrucialitemsthatwecanhaveonourwebsiteinordertoattractviewers.Thisissomethingthatweallwanttodo,right?Also,YouTubeandsimilarsiteshavegainedalotofpopularityandsomepeoplesaythatYouTubeisevenmorevisitedthanGoogle’ssearchpage.Asvideosareinteractiveinsomeway,theycanreallyboosttheviewingofyourwebsite,too!

Let’slookintoeverythingthatwewillcoverinthischapter:

FeaturedimagesHowtosetupandresizefeaturedimagesImagecaptionsImagegalleriesHowtomakeimagegalleriesresponsiveVideos

FeaturedimagesFeaturedimagesareimagesthatshouldrepresentapostorpageonthesideofthecontent.Theyareoptional,whichmeansthatthepostcanhavethefeaturedimageormaynothaveit.Theyusedtobecalledpostthumbnails,butlately,theyhavebeenrenamedtofeaturedimages,asthatisthemoreappropriatename.

Wecansetafeaturedimagebygoingtoasingleposteditor,wpadmin,andchoosingthepostthatwearegoingtoedit.Insidethesingleposteditor,thereistheFeaturedImageoptionontherightsidemenuatthebottomofthepost:

Aswehaveloadedthethemeunittestdata,wedon’thavetocreatethetestingpageourselves.WearegoingtouseTemplate:FeaturedImage(Horizontal),andthepostcanbereachedat:http://localhost/topcat/template-featured-image-horizontal/(ifyouhavethesamesetupasIhave).Ifyoucan’tfinditthere,thenyoushouldgotowpadmin|PostsandsearchforthepostwiththenameTemplate:FeaturedImage(Horizontal).Thispostalreadyhasafeatureimageset:

SettingupafeaturedimageThepostmentionedintheprecedingscreenshot,Template:FeaturedImage(Horizontal),shouldalsodisplayafeaturedimage,butitdoesn’t.So,let’sanalyzethecodetoseewhatisgoingon.Ifwegotothesingle.phptemplate,asthat’sthetemplateforthesinglepost,wewillseethisline:

<?phpget_template_part('content','single');?>

Thislinemeansthatweareloadingacontent-single.phptemplate.So,let’sopenacontent-single.phptemplateandlookforanycodethatmentionsthepostthumbnail.Asthereisnosuchcode,itmeansthatthefeaturedimagefunctionalityisnotimplementedyet,andwecanimplementitwithjustasinglelineofcode:

<?phpthe_post_thumbnail();?>

Withintheheadersection,wecanfindthepostthumbnail:

<headerclass="entry-header">

<?phpthe_title('<h1class="entry-title">','</h1>');?>

<divclass="entry-meta">

<?phptopcat_posted_on();?>

</div><!--.entry-meta-->

<?phpthe_post_thumbnail();?>

</header><!--.entry-header-->

Hereisthenewlookafterourchanges:

NoteAlthoughWordPressisreferringinthecontenteditorasfeaturedimages,thefunctionname(s)handlingthefeaturedimageshavethenamessuchasthe_post_thumbnail,meaningthatfunctionswiththe“oldname”eraassociationsarestillused.

Asouruserscannowloadimagesofallsizes,weshouldsetsizesthatweallowforourfeaturedimages.Wearegoingtosetthisinfunctions.phpjustbelowtheadd_theme_support('post-thumbnails');linethatweenabledpreviously:

add_theme_support('post-thumbnails');

add_image_size('large-thumbnail',600,200,true);

add_image_size('small-thumbnail',300,100,true);

Here,weareusingtheadd_image_sizefunctionwithwhichwewillsetuptwothumbnailssizes:600x200and300x100.ThelatestparameterthatweneedtosettrueorfalseisBoolean.Thetrueoption(thehardcropmode)willjustcuttheimagetofillthecontainerthatweset,andwiththefalseoption(softcropmode),theimagewillberesizedtoitsproposedvalue.

Moreinformationisavailablehere:

http://codex.wordpress.org/Function_Reference/add_image_sizehttp://www.davidtan.org/wordpress-hard-crop-vs-soft-crop-difference-comparison-example/

NoteThecroppingoptionshouldbeused,butaswithanyimportantfeature,itshouldbeusedwiththecaution,asitmaynotworkforallcases.Wehighlyrecommendalwaystestingthoroughlybyaddingimagesandseeingwhethercroppingoptionsareworkingproperly.

ResizingfeaturedimagesAswehaveseensofar,wecansetthumbnailsizesforthemesinfunctions.php,andthat’sreallyagreatthing.Aproblemcouldariseifourenduserloadsourthemetotheirsitethatalreadyhadthumbnailssetfortheiroldtheme.Whentheyloadourtheme,thumbnailswilllookdistorted,astheyweresetfortheothertheme.

Inordertofixthisproblem,wejusthavetoruntheRegenerateThumbnailsplugin,whichweinstalledintheChapter1,ResponsiveWebDesignwithWordPress.Wegotowpadmin|Tools|RegenerateThumbnails,presstheRegenerateThumbnailsbutton,andwewillseetheprocessingscreen:

TipEverytimewechangethethemeonanyofoursites,weshouldrunthisplugininordertobe100percentsurethatthumbnailsinthecurrentthemewillbedisplayedproperly.

Aswehavesetthethumbnailsizes,weshouldimplementthechangeinourcontent-single.phpfilefrom:<?phpthe_post_thumbnail();?>tothis:

<?phpthe_post_thumbnail('large-thumbnail');?>

Aswecanseefromthiscode,weaddedthe'large-thumbnail'parametertothefunctionandifwerefreshthepagenow,theimagewillberesized.

NoteWehavesetthesizeforthethumbnail,butwehaven’tusedsmall-thumbnailyet.Wewilluseitinthenextchapter,wherewewillexplainindexpages.

Finally,ifweresizeourbrowsertothemobilesizescreen,itwilllooklikethis:

Wecanseethattheimagehasbeenresized(theimageisresponsive),andthisisanotherfunctionalitythatwasimplementedbyunderscores.

Thatcodeislocatedinstyle.cssaroundline354:

img{

height:auto;/*Makesureimagesarescaledcorrectly.*/

max-width:100%;/*Adheretocontainerwidth.*/

}

Ifyouwanttoaddmorepropertiestothiscode,feelfreetodoso.

ImagecaptionsImagecaptionsareusedalot,andtheirpurposeistoprovideinformationabouttheimage.Theyareoptional,buttheyshouldbeconsideredforeverytheme,assomepeoplemayusethatfeature.Inordertoseethecaption,weshouldusetheMarkup:ImageAlignmentpost.Then,wecanscrolldowntotheexamplewiththeimagecaptions:

Fromtheprecedingscreenshot,wecanseethatthecaptionbelowtheimagelooksfine.Myadviceistojuststyleitalittlebitinordertomakeitmoredistinguishable.Ifweinspectthefollowingcode,theimagewithFirebug,oranyothercodeinspector,wewillgetthis:

<figcaptionclass="wp-caption-text">

Lookat580×300gettingsome

<ahref="http://en.support.wordpress.com/images/image-settings/"

title="ImageSettings">caption</a>

love.

</figcaption>

Thewp-caption-textitemistheCSSclassthatwearelookingforanditislocatedinstyle.css.So,thecodethatwearelookingtodeleteis:

.wp-caption.wp-caption-text{

margin:0.8075em0;

}

Thiscodeislocatedsomewherearoundtheline1,348.ThechangeIsuggestwedoistomakethetextmoredistinctivebymakingititalicandaddingthesamesilverbackgroundthatweusedforthesidebar:

figcaption{

padding:0.8075em0;

background:#f8f8f8;

font-style:italic;

width:150px;

margin:0;

}

Let’sseeourresultnow:

NoteTherearecaptionsasapartofgalleriestoo.Wewillcoverthisinournextsection,Imagegalleries.

ImagegalleriesImagegalleriesareagreatoptiontoshareimageswithendusers.Wecancreatethegallerybyjustgoingtothesingleposteditorwherewewanttocreatethegallery,andsimplyclickingontheAddMediabutton:

Afterthis,theInsertMediamenuwillshowup:

Here,weshouldclickontheCreateGalleryoption.Whenweclickonthisoption,wewillseeimagesloadedontheright-handside.Then,wejusthavetoclickonimagesthatwewanttoaddtothegallery,clickontheCreateNewGallerybuttonatthebottomontherightside,andthat’sit.

AswehaveloadedaThemeUnitTestdata,wedon’thavetodoallthis,andwehavetwoposts:PostFormat:GalleryandPostFormat:Gallery(Tiled).

HereisthelookofthePostFormat:Gallerypost:

Aswecanseefromtheprecedingscreenshot,thecaptionsaretakingmorespacethanimages.Inordertomakesurethatwearedoingeverythingcorrectly,wehavecreatedanewtestgallery,sowecandouble-checkthedefaultsizeofthumbnails.Whenweloadedallimages,theindividualsizesofthumbnailswere150x150,whichiswhatwewant.weaddedaCSStostyle.cssinordertogetthis150x150sizeforcaptionsinourexistinggallery:

.gallery-itemfigcaption{

width:150px;

}

Ourresultisthis:

Thecaptionisofthesamewidthastheimagenow.Afterthis,weshouldgotothe12.2Galleriessectionandcommentouttext-align:centerinthe.gallery-itemclass:

.gallery-item{

display:inline-block;

/*text-align:center;*/

vertical-align:top;

width:100%;

}

Now,ifwescrolldowninthegallery,wewillseethatsomerowsdon’thaveenoughspacebetweenthem:

Wecansolvethisproblemwithjustonelineofcodeinstyle.css:

figure

{

margin-bottom:0.8075em!important;

}

Let’sviewourresultnow:

MakingthegalleryresponsiveThefinalstepinthecreationofagalleryistomakeitresponsive.Forexample,ifwe,resizethebrowsertothephonesizescreen,wewillgetthis:

Thecaptionisbiggerthanitsimageandimagesarebesideeachother,becausetheseimagesareresponsive(theyresizetogetherwiththescreen,sotheylookgoodacrossalldevices),andthecaptionhasafixedsizeof150px,asyoucanseeitfromourcodeinstyle.css:

.gallery-itemfigcaption{

width:150px;

}

Asthephonescreenistoosmall,weshouldputourimagesintotheirownrowsandtheircaptionsjustbelowthem.Becausewearenowhandlingamobilesizescreen,weshouldputourclassesin@mediascreenand(max-width:480px),whicharelocatedinstyle.css(thesamemediaquerythatweusedforthesidebarandcomments):

.gallery-item{

width:100%;

display:block;

margin:2em1em;

text-align:center;

}

Thiscodecreatesourgalleryitemwithwidthof100%andcenterstheiteminitsrowtoo.Ifwerefreshthebrowsernow,wewillseenochangestoourdivgallery:

<divid="gallery-1"class="gallerygalleryid-555gallery-columns-3gallery-

size-thumbnail">

Thiscodehasaclassofgallery-columns-3,sowehavetomakesurethatitemsinthisclasstake100%width:

.gallery-columns-3.gallery-item,

.gallery-columns-4.gallery-item,

.gallery-columns-5.gallery-item,

.gallery-columns-6.gallery-item,

.gallery-columns-7.gallery-item,

.gallery-columns-8.gallery-item,

.gallery-columns-9.gallery-item

{

max-width:100%;

}

Ifwegobacktothegallerysectionofourstyle.cssfile,wewillseethatwehavecasesthereforgallery-columns-3uptogallery-columns-9,andtheprecedingcodehascovereditall.Ifwerefreshourpageinthemobilesizeview,wewillseeourimagescentered,butourcaptionsleft-aligned:

Let’smakeourcaptionstake100%widthandalignthemtothecentertoo:

.gallery-itemfigcaption{

width:100%;

text-align:center;

}

Hereisourfinallook:

WorkingwithvideosWorkingwithvideosinWordPressisreallyeasy.Forthemajorvideosites(YouTubeorVimeo),wecanjustcopyandpastetheURLintotheposteditorandclickonPublish,andembeddedvideowillappearonourpageorpost:

Now,trytoresizethescreentothemobilesizeandyouwillbepleasantlysurprisedthatthevideoisaresponsive,too.Isn’tthatgreat?

TipThelistofsupportedvideositescanbefoundhere:http://codex.wordpress.org/Embeds.

Aswecanseefromthelink,thelistofsupportedvideositesishuge.If,insomecase,youwouldliketopostavideothatisnotlocatedonthesesites,youwillhavetocreateacustomcodeforit,andthat’soutofthescopeofourbook.

TipYoushouldbeawarethatpostingvideosontheseexternalsitesisthewaytogo,asthisway,youareusingtheirbandwidthandnotyours.Aswithmosthostingcompanies,evenwiththosethathaveunlimitedpackages,thebandwidthislimited(readthefineprint).

SummaryInthischapter,atthebeginning,welearnedmoreaboutfeaturedimagesandhowtosetupandresizethem.Lateron,wetackledtheimagecaptionandlearnedhowtocreatetheimagegalleryandmakeitresponsive.Finally,welearnedaboutvideos.

Inthenextchapter,wewillgetfamiliarwithtemplatefiles.

Chapter8.WorkingwithTemplateFilesTemplatefilesareveryimportantfilesforWordPressthemes.Wehavementionedthispreviously,butlet’srepeatitagain.InordertohaveathemeinWordPress,weneedtohaveatleastthefollowingfiles:

style.css

functions.php

index.php

Instyle.css,wedefinethethemename,adescription,andthecoreCSSforthetheme.Inthefunctions.phpfile,wedefineourowncustomfunctionsandcallingourstylesandJavaScript,andalsowireingourthemecodetotheWordPresscore.Intheindex.phpfile,wedisplaythelistofourposts,pages,oranyotherobjectsthatarelistedinthatindexpage.Therecanbealotofindexpagesinourtemplate.

Withoutfurtherado,inthischapterwewill:

LearnthetemplatehierarchyofarchivepagesLearnmoreaboutexcerptsLearnhowtocustomizethepagingnavigationLearnhowtostylestickypostsModifyarchive.phpModify404.phpModifysearch.php

TheWordPresstemplatehierarchySo,let’sanalyzetheWordPresstemplatehierarchyagain:

Thisistakenfrom:http://codex.wordpress.org/Template_Hierarchy.Ifwestartfromrighttoleft,wehavetheindex.phppage,andthatpagecatchesallrequeststhatarenotexplicitlyhandledbyanothertemplate.Ifwewanttohaveaspecialtemplateforarchives,thenwecancreatethearchive.php(availablewithourtheme)template.Forsearchresults,wecanusesearch.php(availablewithourtheme).Foramissingpage/post,wecanuse404.php(availablewithourtheme).So,ifweexaminetheprecedingscreenshot,wecanseethatarchive.phpisachildofindex.php,andsearch.phpand404.phparechildrenofindex.php.Ifweopenanyofthesepages,wewillseethattheyhaveasimilarstructure(astheyarebootstrappagestoo).Theyjusthavesomecodethatisunique,asithastobelikethatinordertoservethepurposeofapage.Ifwewanttoseethisrelationshipexplainedinreallife,wecanaddthetestingarchivepagetextinthearchive.phppagejustunderget_header();:

get_header();?>

testingarchivepage

Fromthepreviousexplanation,weknowthatthearchive.phppageisanindexpageforarchives,butifwechecktheprecedingscreenshot,wewillseethatit’saparentpageforauthor.php,category.phpandtag.php.Aswedon’thaveanyoftheseavailable,archive.phpcanandwillbeusedasatemplateforthesesituations.Ifwegototheindexpageofourwebsite,wewillseethefirstpostwiththeTemplate:Stickyname.This

posthastagsatthebottom,andifweclickonanyofthetags,wewillseethis:

Weshouldgototheindexpageforthistag(template):

Aswecanseefromtheprecedingscreenshot,ourURL(#1)saysit’satagpageforthe

templatetag:http://localhost/topcat/tag/template/.

Secondly,thetemplatetagnameislistedabovethepost’stitle(#2).

NoteThispagewilllistallpoststhathavethetemplatetagattachedtothem.

Finally,thetestingarchivepagetextthatwehaveaddedtoarchive.phpisshownhere(#3),whichmeansthatarchive.phpwasusedtothatpurpose.Thesamethingwillhappenifweclickonanycategory.Wewillgototheindexpageofthecategoryforwhichourarchive.phppageisused,andwewillseethesametextthatweaddedtothearchivepage.

ExcerptsAswehavealotofpostsloadedwithourtestdataandhopefully,ourcustomerswillhavealotofpoststoo,displayingthefullcontentonindexpagesisnotappropriateasittakestoomuchspace.Ifsomebodyislookingforsomething,it’sreallyconfusing,andittakesvaluabletime.Thisiswheretheexcerptfunctionalitycomestotherescue.

Excerptscanbecustomizedbut,bydefault,theydisplaythefirst55wordsofthearticleandendswith[…],whichiscalledahelliporanellipsissymbol.

Moreinfoisavailableathttp://codex.wordpress.org/Function_Reference/the_excerpt.

Aswehavementionedpreviously,ourindex.phpfileisabootstrapfilewithcallstootherfilesthatprovidepagesections.Theget_template_part('content',get_post_format());lineincludesthecontent-[post_type].phpfile,andifthatfiledoesn’texist,itincludesthecontent.phpfile,whichprovidesthecontent.Inourcase,itincludescontent.php.Supposethatwegotocontent.phpandcommentoutthiscode:

the_content(sprintf(

__('Continuereading%s<spanclass="meta-nav">&rarr;</span>',

'topcat'),

the_title('<spanclass="screen-reader-text">"','"</span>',

false)

));

Andjustleavetheexcerptpart:

the_excerpt().

Hereisthefullcodeexamplewherewehavecommentedoutthe_content()part:

<?php

/*translators:%s:Nameofcurrentpost*/

/*

the_content(sprintf(

__('Continuereading%s<spanclass="meta-nav">&rarr;</span>',

'topcat'),

the_title('<spanclass="screen-reader-text">"','"</span>',false)

));

*/

the_excerpt();

?>

Wewillhaveourexcerptdisplayedonourindexpage,asyoucanseeonthefollowingimage:

Isn’tthiseasy?TheonlypartmissinghereistheReadMorebutton(link).Wealsohaveafootertherewithtagsandoptiontoleavethecomment,andthisisreallynotneededontheindexpage,sowewilltakethefooterout:

<?phptopcat_entry_footer();?>

Replacethisline(incontent.php)withtheReadMorelink:

<?phpecho'<ahref="'.get_permalink().'"title="'.__('ReadMore',

'topcat').get_the_title().'">ReadMore&nbsp;&nbsp;<iclass="fafa-

arrow-circle-o-right"></i></a>';?>

Asyoucansee,wehaveaddedtheawesomeiconfonttothecode:

Now,wejusthavetostylethelinkproperly,andthat’sit.WewilldothisinthePostsandpagessection(10.1)ofstyle.css.

Attheendofthesection,weshouldputthiscode:

.entry-footer,

.entry-footera,

.entry-footera:visited,

.entry-footera:active

{

color:#000;

font-weight:600;

font-family:"OpenSans",sans-serif;

text-decoration:none;

}

.entry-footera:hover

{

color:#0480b5;

font-family:"OpenSans",sans-serif;

text-decoration:underline;

}

Thefirstpartistomakethelinksblackandboldinordertomakethemmoredistinctivefromthecontenttext,makethemundecorated(meaningnounderline),andassignthemafontfamily.Onhovering,wecolorthetextwithblueandgiveitanunderlinedecoration.

FeaturedimagesThenextstepistoputfeaturedimagesinthecontenttemplate,andallittakesisaddingoneline:

<headerclass="entry-header">

<?phpthe_title(sprintf('<h1class="entry-title"><ahref="%s"

rel="bookmark">',esc_url(get_permalink())),'</a></h1>');?>

<?phpif('post'==get_post_type()):?>

<divclass="entry-meta">

<?phptopcat_posted_on();?>

</div><!--.entry-meta-->

<?phpthe_post_thumbnail('small-thumbnail');?>

<?phpendif;?>

</header><!--.entry-header-->

TipPostthumbnailsorfeaturedimages

Whilelistingtheexcerptsofposts,wewanttoalsoshowtheirpostthumbnail—iftheyareavailable.Thisiswhyfeaturedimagesarealsocalledpostthumbnails—likethumbnailsinagallery,theyrepresentthepostinthelistcontext.

Ifyouremember,wehaveaddedthetwosizesofpostthumbnailsintheChapter6,ResponsiveWidgets,Footer,andComments,andweusedonlythelargeoneforthesinglepost.Fortheindexpage,weareusingasmallthumbnail:

Wecanseeasmallthumbnail(#1)andthelookoftheReadMorelink(#2)intheprecedingscreenshot.

CustomizingthepagingnavigationIfwescrolltotheendoftheindexpage,wewillseetheOlderpostslink:

Thisispartofourcurrentnavigation.Thegoodthingwiththisnavigationisthatwehaveitandthebadthingisthatisreallysimpleandifwehavealotofposts,thisnavigationisnotthathelpful.Pagingwillbemorehelpful,astherewewillhaveboxeswithpagenumbers.Thenwewillbeabletoskipmorepagesatthesametimeinsteadofjustgoingfromonepagetoanother.Ournavigationcodeiscontainedinthetopcat_paging_nav()functionthatislocatedinthetemplate-tags.phpfilewithothercustomfunctions.Aswewanttousethemoresophisticatedsolution,Ihavefoundthecodethathasapagingfunctionality(thiscodeisactuallyusedintheTwentyFourteentheme,thathasbeentestedalotandbecauseofthatitisgood).

TipTheupdatedtemplate-tags.phpfileisprovidedwiththecodeforthischapter.

Makesurethatyouchangetheinstancesoftheword(domain)fromtwentyfourteentotopcatinthiscode.

Hereistheexample:

"'prev_text'=>__('<iclass="fafa-arrow-leftfa-4"></i>Previous',

'twentyfourteen'),"

"'prev_text'=>__('<iclass="fafa-arrow-leftfa-4"></i>Previous',

'topcat'),"

Hereisthecodesectionwherewehavetomakechangesforthenavigationlocatedin/inc/template-tags.php:

//Setuppaginatedlinks.

$links=paginate_links(array(

'base'=>$pagenum_link,

'format'=>$format,

'total'=>$wp_query->max_num_pages,

'current'=>$paged,

'mid_size'=>1,

'add_args'=>array_map('urlencode',$query_args),

'prev_text'=>__('<iclass="fafa-arrow-leftfa-4"></i>Previous',

'topcat'),

'next_text'=>__('Next<iclass="fafa-arrow-rightfa-4"></i>',

'topcat'),

));

Hereisthecurrentlookofthepagingnavigation:

Now,let’sstartwithstylingourpagination:

.pagination,

.paginationa,

.paginationa:visited,

.paginationa:active

{

color:#0480b5;

font-family:"OpenSans",sans-serif;

font-size:1.6rem!important;

font-size:16px;

line-height:16px;

text-transform:uppercase;

font-weight:800;

padding:10px;

font-style:normal;

text-decoration:none;

}

Inthepreviouscode,wearecoloringourpaginationinblue,wearemakingfontstobeuppercaseanda1.6remsize,andfinally,wearemakingsurenoneofthelinksareunderlined.Takealookatthiscode:

.pagination.current

{

color:#666;

}

Inthenextcode,wearecoloringhoverlinkstodarksilverandwearemakingsurethatonhovering,theywillbeunderlined:

Inthefollowingcode,wearecoloringcurrentpagenumbertodarksilver:

.paginationa:hover

{

color:#666;

font-family:"OpenSans",sans-serif;

font-size:1.6rem!important;

font-size:16px;

line-height:16px;

text-transform:uppercase;

font-weight:800;

padding:10px;

font-style:normal;

text-decoration:underline;

}

Withthiscode,wearemakingsurethatourpaginationiscentered,asitlooksbetterlikethat:

.pagination

{

text-align:center;

}

TheoriginalpaginationusedHTMLspecialcharactersforarrows,butasweareusingthefontawesomeforthemonothersections,itwillbeappropriatetouseitforthisnavigationtoo.Inordertousethefontawesomefonts,wehavetochangethecodeintemplate-tags.php:

$links=paginate_links(array(

'base'=>$pagenum_link,

'format'=>$format,

'total'=>$wp_query->max_num_pages,

'current'=>$paged,

'mid_size'=>1,

'add_args'=>array_map('urlencode',$query_args),

'prev_text'=>__('<iclass="fafa-arrow-leftfa-4"></i>

Previous','topcat'),

'next_text'=>__('Next<iclass="fafa-arrow-rightfa-4"></i>',

'twentyfourteen'),

));

Changesaremarkedinboldinthepreviouscode.Afterthis,wehavetomakechangesinstyle.css.Aswewantthesearrowstobesmallerthanthearrowsinothersections,wewilluse.fa-4(fontawesome4class),andbecausethefontsarethesizeof16px,weshouldhavethefontawesomeiconstohavea16pxsize,too:

.fa-4{

font-size:16px;

font-size:1.6rem!important;

}

Also,wewanticonstochangecoloronthehovertoourdarksilvercolor.Toachievethis,wewillusethefollowingcode:

.paginationa:hover.fa-arrow-right,

.paginationa:hover.fa-arrow-left

{

color:#666;

}

StylingstickypostsStickypostisthemostimportantpostthatwewanttoshowatthetopofallposts,evenbeforethelatestposts.Aswehavementionedpreviously,wecancheckwhetherourpostissticky;ifwegototheposteditorandatthetop-rightPublishsection,itwilldisplaythis:

Ifit’snotastickypostandwewanttomakeitsticky,weshouldjustclickontheEditbuttonandchecktheStickthisposttothefrontpageoption:

Ifthepostisasticky,WordPressaddsastickyclasstothemarkup:

<articleclass="post-1241posttype-poststatus-publishformat-standard

stickyhentrycategory-uncategorizedtag-sticky-2tag-template"id="post-

1241">

TipBydefault,WordPressaddsastickyclasstothemarkuponlyundercertaincircumstancesonindexpagesbutnotonsinglepostpages.

Then,wejusthavetofindthestickyclassinourstyle.cssfileandaddtheborderand

padding:

.sticky{

display:block;

border:1pxdashed#666;

padding:10px;

}

Let’sseeourresult:

Modifyingarchive.phpAswehavementionedatthebeginningofthischapter,whileanalyzingthefirstimage(thetemplatehierarchy),thearchive.phptemplateistheparenttemplateforarchivesforauthors,categories,posttypes,taxonomies,dates,andtags.Overall,itdisplaysthearrayofpoststhatmatchthespecificposttype(mentionedpreviously).

Wehavetestedthisfunctionalitybyclickingonacategoryorataginourindexpage,andwegottheoutputfromarchive.php.Takealookatthecodeinarchive.php:

Wewillseethattheoutputisjustabasicone.Forexample,iftheenduserclicksontheTemplatecategory,he/shewillgetthisoutput:

Thecategoryname(Template)willbedisplayedabovethetitle,butitdoesn’tsayanywherewhetherthat’sacategory,atag,orsomethingelse.Byaddingjustonelineofthecode,wewillmakeitmoreexplicit:

echo(__('Category:','topcat'));

single_cat_title();

Wecanmakethesamechangewithtags:

echo(__('Tag:','topcat'));

single_tag_title();

Theonlythingthatweshouldchangeisthecolorofthattitle,asit’scurrentlythesamecolorastheposttitleandit’shardtodifferentiatethem.Wecanperformthischangebyaddinganarchive-titleclasstothisline:

<h1class="page-titlearchive-title">

Withjustaddingthearchive-titleclasstoourstyle.cssfile:

.archive-title{

color:#666;

}

Weshouldaddthiscodeto10.1sections:Postsandpages.Ourfinalresultis:

NoteWewillgetthesamelookifweclickonanytagsinsteadofcategories,asarchive.phpisafallbacktemplate.

Modifying404.php404.phpisthepagethatshowsthewarningmessagewhenendusertriestogotoapagethatdoesn’texists,forexample:http://localhost/topcat/page1234asyoucanseeinthefollowingimage:

Here,wefirstsearchfortheterm(#1),andthenwegetthemessage(#2).Belowthemessage,wegetthesearchbox(#3)—sameoneasinsearch.php—sowecansearchforsomethingthatexistsinthesystem,asmaybe,wehavemisspelledthepage.Belowthat,weseesomeotherwidgets(#4)—RecentPosts,MostUsedCategories,andsoon—thatwillgiveusmoreoptionstofindthestuffthatwearelookingfor.So,atfirst,weshouldchangethecolorofthetitlebyaddinganarchive-titleclasstothisline:

<h1class="page-titlearchive-title"><?php_e('Oops!Thatpage

can&rsquo;tbefound.','topcat');?></h1>

Aswedon’thavethesidebaronthispageanditcanbehelpfultoenduser,weshouldadd

ittooursearch.phppagejustbeforethecallforthefooter:

<?phpget_sidebar();?>

<?phpget_footer();?>

Let’sseehowourpagelookslikeafterthechanges:

Itlooksprettygood,right?

Modifyingsearch.phpThesearch.phpfileisinthesamelevelasarchive.phpanditspurposeistoshowtheresultsofthesearch,andiftherearenoresults,itshouldshowthemessage.Aswealreadydidalotofcustomization,wejustneedtodothebasicstylingandtestthesearch.Atthismoment,wedon’thaveasearchform,butwecantestthesearchbyaddingparameterstotheURL,forexample:

http://localhost/topcat/?s=test

Here,weareaddingthe?s=testparameter,whichmeansthatwearesearchingforanypostorpagethatcontainsthetestterm.Ourresultis:

Theresultlooksgood,aswehavefoundthematchesforoursearch.Theonlythingthatweshouldchangeisthecolorofthepagetitle;inourcase,thisisSearchResultsfor:test;todistinguishitfromtheposttitle,TESTGALLERY.Inordertodothis,wejusthavetogotosearch.phpandaddthearchive-titleclasstothisline:

<h1class="page-titlearchive-title"><?phpprintf(__('SearchResults

for:%s','topcat'),'<span>'.get_search_query().'</span>');?></h1>

Thisistheresult:

SummaryInthischapter,wehavelearnedaboutthehierarchyoftemplatefiles,excerpts,howtocustomizethepagingnavigation,howtostylestickyposts,archive.php,404.php,andsearch.php.

Inthenextchapter,wewillworkonstaticpagesandtheirtemplatesandwewilllearnhowtoaddextrafunctionalitywithplugins.Wewillcoverthehomepage,asitslayouthasmoreelementsthanotherpagesanditdoesn’thaveasidebar,whichmeansthatwewilladdanotherCSSfileforthatcase.

Chapter9.WorkingwithStaticPagesandAddingtheExtraFunctionalitywithPluginsWehaveleftthebestforlast.Withthischapter,wearewrappingthedevelopmentpartofourbook.

Postsareentrieslistedinreversechronologicalorderonthebloghomepageoronthepostspageifyouhavesetonewpadmin->Settings->Reading.Ifyouhavecreatedanystickyposts,thosewillappearbeforetheotherposts.IfyouareusingWordPressasabloggingplatformyouwillbemostlyusingpoststhere.Youcanorganizeyourpostsbyusingcategoriesandtags.

Pagesarestaticandarenotlistedbydate.Pagesdonotusetagsorcategories.AnAboutpageistheclassicexampleofastaticpage.

StaticpagesareacrucialpartofWordPressthemesaswearegivingourcustomerspremadesolutionsthattheycanconfiguretotheirneeds.

Let’sseewhatwewillcoverinthischapter:

CreatingandassigningthepagetemplateCreatingalternativestylesforthehomepageSettingthesliderpluginSettingtheservicespluginCheckingwhetherthereareservicesandhowtolistthemMakingthehomepageresponsiveCreatingtheContactUspagewithacontactuspluginthatisapartofJetpack

HomepageHomepageisthelandingpageofourwebsiteanditspurposeistoattractcustomersandprovidethemostimportantinformation.Ashomepageusuallyhasadifferentlookthanotherpages,wehavetocreateacustomcodeinordertomatchourneeds.Hereisthelookthatwewantforourhomepage:

Aswecanseefromtheprecedingscreenshot,wewillhavethreesectionsthere:theslider(1),shortdescription(2)andthelistofservices(3).Allthesefeaturesareoptional,althoughIadviseusingthemall,astheybecameade-factostandardforbusiness-orientedtemplatesinthelastfewyears.

NoteIfyouwanttoknowmoreaboutthefeaturesforbusinesstemplates,checkthefollowingsites:

https://wordpress.org/themes/search/business/

http://themeforest.net/category/wordpress/corporate

Here,youwillseethatamajorityofthemeshavethefeaturesthatIhavejustmentioned

ThehomepagetemplateAswehavementioned,wearegoingtocreateacustomtemplatethatwillservethepurposeofthehomepage.Inordertodothiswehavetogoinoureditorandcreatethefront-page.phpfile.Inthisfile,weshouldaddthefollowingcode,inordertomakethisfileapagetemplate:

/*

TemplateName:HomePage

*/

Whenweaddedthiscode,wegotanewoptioninourpageeditor.However,beforewemakeanychanges,weshouldgotothepageeditorbynavigatingtowpadmin|Pages|AddNewandcreateanewpagewiththeHomename.Afterthis,wewillbeabletoseethetemplatedropdowninthePageAttributessectionontheright,andthere,weshouldchoosetheHomePagetemplate:

Thatishowweassignthetemplatetothepageineditor.

TipWecouldassignanythingtothetemplatename.WearejustusingTemplateName:HomePageforconsistencyandtomakeourlifeeasier,asthistemplatenameisclearlysayingwhatthistemplateisabout.

Now,weshouldgotoAppearances|CustomizeinwpadminandassignaHomepageasStaticFrontPage:

Inthepreviousimage,inthestep#1,wearechoosingaradiooptionAstaticpage,andinstep#2,wearechoosingourHomepagefromthedropdown.Now,whenweclickonahomelinkinourmenuoronalogo,wewillbetakentoournewhomepage.

StylesforthehometemplateAswewereabletoseefromthefirstimageatthebeginningofthischapter,ourhomepageisgoingtolookdifferentthanotherpages.Itwillnothavetherightsidebarandthecontentwilltake100percent.Becauseofallthis,weshouldhaveaseparateCSSfileforthispurpose.

TipAswealreadyhaveacontent-sidebar.cssfileinourlayoutsfolder,Irecommendthatyoucreateacopyofthisfile.Wecanreusealotofcodethereandweshouldnamethenewfilecontent.css.

Inordertousecontent.cssonourhomepage,wehavetoaddthiscodetoourfunctions.phpfile:

if(is_page_template('front-page.php')){

wp_enqueue_style('topcat-layout-css',get_template_directory_uri().

'/layouts/content.css');

}

else

{

wp_enqueue_style('topcat-layout-css',get_template_directory_uri().

'/layouts/content-sidebar.css');

}

Inthecontent.cssfile,weshouldmakesomechanges.Forexample,weshouldchangethisclass:

.site-main{

margin:05%00;

}

Tothefollowing:

.site-main{

margin:0;

}

Weshouldalsodeletethe.site-content.widget-areaclass,aswearenotgoingtousethewidgetareainthistemplate.

Then,inthedesktopstylesmediaquery:

/*desktopstyles*/

@mediaonlyscreenand(min-width:769px){

Weshouldmakethecontentareataking100%insteadof70%,anddeletethefloat,aswedon’tneedit:

.content-area{

width:100%;

}

Inordertodisplaythecontententeredintheeditorinourhometemplate,wehavetoadd

thiscodetohome-page.php:

<?phpif(have_posts()):while(have_posts()):the_post();?>

<?phpthe_content();?>

<?phpendwhile;endif;?>

SliderpluginAswewanttomakeoursitemoreinteractive,weshouldinstallasliderplugin.Therearealotoffreeandpremiumsliderpluginsthatwecoulduse,butasthisisatrainingbook,wewillusethefreeonesothateverybodycanhavetheaccesstoit.Forthispurpose,wewilluseaMetaSlider,whichiscurrentlythemostpopularfreesliderpluginontheWordPress.orgwebsite.

Itcanbedownloadedfromhere:https://wordpress.org/plugins/ml-slider/.

NoteFormyprofessionalprojects,IwasusingaLayerSlider,whichisapremiumplugin.Youcancheckitouthere:http://codecanyon.net/item/layerslider-responsive-wordpress-slider-plugin-/1362246.

ThegreatthingwithourMetaSliderpluginisthatwecansetitupinitsowneditor,grabashortcode,pasteitinourpage,andthat’sit.Shortcodesarecustomfeaturesthatcanbecalledfromthepostorpageeditor;forexample,gallerycanbecalledwith[gallery].OurMetaSliderwillbecalledwiththiscode:[metasliderid=1734].

Now,let’ssetuptheslider:

Here,weshouldfirstaddthefirstslide,andthenchoosetheimage(#1),generaldescription(#2),andURL(#3).

NotePleasenotethatIdidn’tchooseanythingforourURLsatthispoint.

Then,weshouldchoosewhichsliderwewanttouse,asMetaSliderhasmanyoptions.Inthiscase,let’susethefirstoption:Flexslider(#4).Asourcontentwidthis1000px,weshouldchooseawidthof1000px(#5),tooandaheightof273px(#6).

Note

ThesesizesworkwithimagesthatIhaveused,andIrecommendthatyouusethesameimages.

TheseimageswereprovidedasapartoftheThemeUnitTestDataandwecanfindthembyjustchoosingtheAddslideoptioninMediaLibrary,andtheyshouldbesomewhereonthefirstpage.

Afterdimensions,weshouldchoosetheFadeeffect(#7)andtheDefaulttheme(#8),andweshouldalsoselecttheArrowscheckbox(#9)andDotsforthenavigation.Let’slookattheadvancedsettings:

Intheadvancedsettings,weshouldchoose:

TheStretchoption(#1)Centeralign(#2)Autoplay(#3)Hoverpause(#4)PrintCSS(#5)PrintJS(#6)

Forthefinalstep,weshouldcopytheshortcodefromtheusagesectionandpasteitinthepageeditor:

Inourcase,thecodeis[metasliderid=1734],andinyourcase,thecode(idnumber)maybedifferent.

TheServicessection(listofservices)Inthissection,wewillcreatetheoptiontolistservices,andinordertodothat,wehavetocreatetheoptionforouruserstoaddservices.Thebestwaytodothisistousetheplugin,whichwilladdcustompostservicestoourwpadmindashboard.

NoteCustompostshelpenduserdifferentiateonetypeofpostfromotherasinthedatabase,allpostsaresavedonthesameplace.Inourexample,ourusercanchoosetheservicesoptioninwpadminandaddnewservices.Lateron,whenwewanttoshowresults,wearegoingtosearchforpostsofthetypeservicetodisplay.

Ihavecreatedthepluginthatwilladdcustomposttypeservicestowpadmin,andthisplugincanbedownloadedfromhttps://github.com/dejanmarkovic/nyto-services-cpt.

Whenwedownloadtheplugin,wewilljusthavetoinstallandactivateit,andthenwewillseetheServicesoptioninwpadmin:

Then,weshouldgothereandaddnewservices,sameasweaddanyotherpostorpage:

Inthestep1(#1),wewillpresstheAddNewbuttontoaddanewservice,andinthestep2(#2),wecanseetheservicesthatarealreadyadded.

NoteInyourcase,youwillhavetoaddservicesfirstinordertoseetheresultsinthestep2.

Afterweaddservicestooursystem,weshouldgoandhandletheresultsinourfront-page.phpfile:

First(#1),wecheckwhetherourpluginisinstalledandactivated.Ifthepluginisnotthere,weshouldnotdisplaytheservices.Thismeansthatifourenduserinstallsthepluginandaddstheservicesbutlateron,changeshis/hermindanduninstallstheplugin,theservicesshouldnotbedisplayed.Next(#2),weexecuteaqueryfirstinordertogetpostsofthetypeofservice;then(#3),wecheckwhetherthereareanyservicesinthedatabase,andifthereare,thenwewilldisplaythem;ifnot,wewillnotdisplayanythinginthissection.Asyoucansee,eachofthesectionsisoptional,aswehavementionedpreviously.Lateron(#4),wedefinea$service_classvariablethatisgoingtobeusedasaCSShelperforourlayout.

Next(#5),wecheckwhetherthereare4orlessservicesinthedatabase,asthissolutioniscustomizedforuptofourservices.

NoteThiscodecanhandleonlyupto4services,andthatwillbeenoughforourproject.

Lateron(#6),wearedoingacalculationforourserviceclass;ifthereisonlyoneserviceinthedatabase,theservicessectionwilltake100percentofthatwidth;ifthereare2services,theywilltake50percenteach;ifthereare3services,eachservicewilltake33

percent;ifthereare4services,eachservicewilltake25percent.Forthesecases,wearegoingtouseCSSclasses’perc33,perc25,andsoon:

/*percentagesizeofservicesboxes*/

.perc33{

max-width:33%;

}

.perc25{

width:25%;

}

.perc100{

width:100%;

}

.perc50{

width:50%;

}

NoteThisCSScodeshouldgotothecontent.cssfile’sdesktopstylesmediaquery:

/*desktopstyles*/

@mediaonlyscreenand(min-width:769px)

Next(#7),weaddclasseswhichmakesurethatserviceswillbecenter-aligned:

/*alignservicestocenter*/

.inline-block-center{

text-align:center;

}

.inline-block-centerdiv{

display:inline-block;

text-align:left;

}

NoteThisCSScodeshouldgotothestyle.cssfile.

Lateron(#8),weloopthroughthelistofservices:

<?phpwhile($loop->have_posts()):$loop->the_post();?>

Next(#9),weadd$service_class,whichhasthepercprefix(thepercentage).

Then(#10),wedefinetheservicestitleandaddaservice-titleclass.Weshouldalsoaddthestylingtostyles.cssfortheservice-titleclass:

.service-title{

color:#0480b5;

font-size:2.2rem;

font-size:22px;

line-height:22px;

text-transform:uppercase;

font-family:'OpenSans',sans-serif;

text-align:center;

}

NoteThisCSScodeshouldgotothestyle.cssfile.

Next(#11),weaddtheservice-contentCSSclasstothemarkup,andthecodeforthatclassshouldbethefollowing:

.service-content{

margin:20px;

}

Finally,(#12)wearedisplayingthecontentpartwiththe_content()function.

Asourservicesarenestedinthe<section>tag,hereismoreofCSScodethathandlesmargins,padding,andaborder:

.services_section

{

margin:20px0px;

padding:10px;

}

sectiondiv{

padding:15px;

margin:5px;

border-left-style:solid;

border-left-width:1px;

display:table;

border-color:#ececec;

}

sectiondiv:first-child{

border-left-width:0;

}

NoteThisCSScodeshouldgotothecontent.cssfile’sdesktopstylesmediaquery:

/*desktopstyles*/

@mediaonlyscreenand(min-width:769px)

TipTheservicesfunctionalityisanextrafunctionality,whichmeansthatitisnotadesign/themefunctionalityandbecauseofthat,itshouldbeputinapluginasaseparatefeature.Withthisoption,wegiveourenduserachoicetousethatfunctionality(ornot)andatthesametime,wefollowthebestWordPresspractices(inthiscase,separatingthecontentfromdesign).HereisthelinktoagreatarticleatWPTavernthatexplainswhywe(thethemedevelopers)aredoingthis:http://wptavern.com/why-wordpress-theme-developers-are-moving-functionality-into-plugins.ThereisagreatlibrarycalledtheTGMPluginActivationthatwecanusetorequiretherecommendedplugins,anditcanbedownloadedfromhttp://tgmpluginactivation.com/.Coveringthislibraryisoutofthe

scopeofthisbook,butIstronglyrecommendthatyouuseit.

MakingourhomepageresponsiveWehavealreadystartedmakingourhomepageresponsivebyaddingsomecodetothecontent.cssdesktopstylemediaqueries.Now,weshouldmakesomeclassesmobilephonefriendly,andwewillexecuteallthesechangesinthemobilephonestylesmediaqueryinthecontent.css@mediaonlyscreenmax-width:480px.

Atfirst,wedon’treallyneedaslideronthemobilephonesizescreen,soweshouldhideit:

.metaslider{

display:none;

}

Then,weshouldtakethedisplay,flex,andtheborderfromsection:

section{

margin:20px0px;

padding:10px;

}

sectiondiv{

padding:15px;

margin:5px;

border-left-style:none;

}

sectiondiv:first-child{

border-left-width:0;

}

Finally,wehavetocustomizeourpercentageforservices’CSSclasses:

.perc33{

max-width:100%;

display:block;

}

.perc25{

max-width:100%;

display:block;

}

.perc100{

max-width:100%;

display:block;

}

.perc50{

max-width:100%;

display:block;

}

Withthiscode,eachservicewillgointoitsownrow.

Hereisthefinallookonthemobilephonesizescreen:

TheContactUspageWhatwouldbethepurposeofourbusinesssiteifourcustomerscan’tcontactus?Thisiswhywearegoingtocreateacontactuspage.Beforewedothis,weshouldinstalltheJetpackpluginasoneoftheoptionshasacontactformplugin:

First(#1),wecanseetheContactFormoption,andthen(#2),weshouldclickonActivatetoactivatethecontactform.

Afterweactivatethisoption,weshouldcreatetheContactUspage,andintheeditor,wewillbeabletochoosetheAddContactFormoption:

AfterclickingonAddContactForm(#1),wewillseetheformbuilderwherewewillbeabletochoosefieldsthatwewanttouse:

NoteThisformdoesn’thaveanykindofcaptchaoption,asitisdirectlywiredtotheAkismetservice,soitdoesn’treallyneedit.

Finally,afterweacceptalltheoptions,theshortcodewillbeaddedtoourform:

Wewilljusthavetopublishthepage,andthat’sit:

SummaryInthischapter,wehavelearnedaboutstaticpages,slider,shortcodes,howtomakeourhomepageresponsive,andhowtocreatethecontactuspage.

Bynow,youshouldhaveabasicunderstandingofthedevelopmentofaresponsivethemeinWordPress.

Now,theonlythinglefttodoistolearnhowtotestourthemeandhowtoproperlysubmitittoWordPress.orgbyfollowingtheWordPressCodex.

Withoutfurtherado,let’smoveontoourfinalchapter.

Chapter10.SubmittingYourThemetoWordPress.orgIfyouhavebeenpatientenoughtostickwithusuntilhere,youshouldhaveaclearunderstandingofWordPress’sresponsivethemedevelopmentandthestepsinvolvedinit.YourresponsiveWordPressthemelooksbeautifulandthereisonlyonethinglefttodobeforeyouintroduceittotheworld.Yeah,youguesseditcorrectly.

Inthischapter,youwilllearnaboutfine-tuningyourthemetofollowtheWordPressCodexinordertosubmitittotheWordPress.orgrepository.

Thereisstillalotofworkleftandwithoutfurtherado,inthischapter,youwilllearnabout:

PolishingcodebeforesubmissionApplyingtheeditorstylesValidatingtheHTMLandCSScodeValidatingtheJavaScriptandPHPcodeAddingthereadme.txtfileAddingthescreenshot.pngfileRunningathemecheckpluginSubmittingyourthemetoWordPress

PolishingcodebeforesubmissionInorderforourthemetobeaccepted,wehavetomakesureitmeetsthestandardsofWordPress.org,andinordertodothatwehavetotestitandapplyproperfixes.IhaveintentionallysavedthisforthelastchapterasthisshouldbethemostimportantstepbeforewesubmitthecodetotheWordPress.orgrepository.Solet’sdothistogether.

NotePleasecheckthelook/behaviorbeforeandafterapplyingeachchangeasthatisthebestwaytolearn.

Let’stakealookatthefollowingsteps:

1. Onafront-page.phpfilepleaseaddthiscode:

<?phpinclude_once(ABSPATH.'wp-admin/includes/plugin.php');?>

Thepreceedingcodeisaddedjustbeforethecodethatcheckswhetherthenyto-servicespluginisinstalled:

<?phpif(is_plugin_active('nyto-services-cpt/nyto_services_cpt.php'

)){

Thiscodeisaddingtheplugin.phplibrarytothefrontendpagesasthislibraryisusedonlyinwp-adminbackend.Ifwedon’taddthiscodetoourhomepage,itwillbebroken.

2. Whenwecheckourthemeonthecellphone,ourmainnavigationisexpandingtoomuchonthesectionswherewehavechildelements.Tofixthis,deletetheposition:relative;propertyinside.main-navigationululdeclarationwhichislocatedaroundline623instyles.css.

3. Wewanttohaveproperpaddingforourcontentwhenviewedonalldevices.Thebestwaytodothisistodeletepaddingpropertiesfromclass.content-areainallmediaqueries(desktop,tablet,andcellphone)andjustaddthiscode:

.content-area{padding:3rem;

}

Theprecedingcodeneedstobeaddedtotheneutralarea(areabeforethosequeries)inthecontent-sidebar.cssfile.Wearenotaddingthatcodetothecontent.cssfileastherewehavethesliderandcodefromtheservicesplugin,andthatcontentdoesn’tneedanypadding.

4. Tomaketheheadersectionwithsitebrandinglookbetter,deletethiscodefromstyle.css:

.logo-container{

padding:010px;

}

Then,addthefollowingcodetoendofthestyle.cssfile:

.site-branding{

padding:1rem;

}

Withthiscode,weareaddingapaddingof1remtoourlogo

5. Instyle.css,findthe.site-footer.widgetclassandchangeitwiththiscode:

.site-footer.widget{

float:left;

margin:01rem2rem0rem;

width:30%;

}

Thiscodemakessurethatwidgetmarginsareproper(textorimagesarenotgoingoutsideoftheirblocks)

6. Ifweareloggedininfrontendpreview,thewp-admintoolbarmaybebroken.Justdeletewp_deregister_style('open-sans');fromfunctions.phpinordertofixthebrokenwp-admintoolbarinfrontendview.

7. Wewanttomakethesite’staglinetobeofthesamecolor:

Instyle.css,findthe.site-descriptionclassandchangethecolorpropertyfrom#2B2B2Bto#0480B5

Incontent-sidebar.css,findthe.site-descriptionclassanddeletethecolorpropertytogetherwithitsvalue

Incontent.css,findthe.site-descriptionclassanddeletethecolorpropertytogetherwithitsvalue

8. Wenowwanttoimprovethelookofservicesthatarelistedonourhomepage.Sincewehavebordersandpaddingsthere,weshouldupdatethoseclassesincontent.css:

.perc33{

max-width:31%;

}

.perc25{

width:23%;

}

.perc50{

width:47%;

}

Aswecanseefromtheprecedingcode,wehavejustreducedthevaluesinordertomaketheservicesfitinonerow

Also,weshouldaddthiscodetocontent.cssinordertomakesureourservicesaretop-aligned:

.perc33,.perc25,.perc50,.perc100{

vertical-align:top;

}

9. Wealsohavetomakesurethatourbluecoloristhesameinallplaces,soinstyle.css,changethebackgroundcolorfrom#579DB5to#0480B5aroundlines542,

560,581,585.

Instyle.css,online505,weshouldchangefont-weight:800;tofont-weight:500.

Instyle.css,online524,weshouldaddborder-right:1pxsolid#666;.

Instyle.css,online527,considerthefollowingcode:

.main-navigationa{

font-size:15px;

font-size:1.5rem;

display:block;

text-decoration:none;

color:white;

padding:14px10px;

}

Changetheprecedingcodeto:

.main-navigationa{

color:#FFF;

display:block;

height:auto;

margin:0;

padding:14px10px;

text-decoration:none;

}

Wehaveaddedheight:autohereandhavetakenoutthefontsizes.

Instyle.css,online559,considerthefollowingblockofcode:

.main-navigationli:hover>a{

color:#FFF;

background:#0480B5;

}

Changethistothefollowingblockofcode:

.main-navigationli:hover>a{

color:#FFF;

background:#543018;

}

Here,wehavechangedthebackgroundcolorfrombluetobrown.

Instyle.css,online566,considerthefollowingcode:

.main-navigationulula:hover{

background:#0480B5;

}

Changethistothefollowingblockofcode:

.main-navigationulula:hover{

background:#543018;

}

Wehavechangedthebackgroundcolorherefrombluetobrown.

Instyle.css,online578,considerthefollowingcode:

.main-navigation.current_page_item>a,

.main-navigation.current-menu-item>a,

.main-navigation.current_page_item>a:hover,

.main-navigation.current-menu-item>a:hover{

background:#0480B5;

}

Changethistothefollowingblockofcode:

.main-navigation.current_page_item>a,

.main-navigation.current-menu-item>a,

.main-navigation.current_page_item>a:hover,

.main-navigation.current-menu-item>a:hover{

background:#543018;

}

Wehavechangedthebackgroundcolorherefrombluetobrown.

Incontent-sidebar.cssandcontent.css,in@mediaonlyscreenand(min-width:769px)and@mediaonlyscreenand(min-width:481px)and(max-width:768px),addthefollowingcode:

#menu-main-menuli{

width:130px;

text-align:center;

}

Herewearemakingmenusizefixed,130pxonthedesktopandtablet.

Incontent-sidebar.cssandcontent.cssinmediaqueryforphones,addthiscode:

@mediaonlyscreenand(max-width:480px)

#menu-main-menulia{

width:100%;

}

Wearemakingmenuitemstohaveawidthof100%inmobilestyles.

Instyles.css,addthiscodetoendoffile:

.main-navigation

{

font-size:1.2rem;

font-size:12px;

}

Herewearemakingmenuitemstohavethefontsizeof1.2rem.

Finally,wehavetomakesurethatallmenuitemsarehavingthesamerightborder.Inordertodothat,wehavetoaddthisfixtoglobal.js:

jQuery("#menu-main-menu").addClass('clear');

varcontainerheight=jQuery("#menu-mainmenu").height();

jQuery("#menu-main-

menu").children().css("height",containerheight);

10. Infunctions.php,findthiscode:

add_theme_support('custom-header',apply_filters(

'topcat_custom_header_args',array(

'default-image'=>'',

'default-text-color'=>'000000',

'width'=>150,

'height'=>200,

'flex-height'=>true,

'wp-head-callback'=>'topcat_header_style',

'admin-head-callback'=>'topcat_admin_header_style',

'admin-preview-callback'=>'topcat_admin_header_image',

)));

Here,changethewidthandheightasfollows:

'width'=>220,

'height'=>100,

Ithinkthatthelogowithbiggerwidthandsmallerheightwillfitbetteronourtemplateandthisisthefix.

ApplyingtheeditorstylesBeforewesubmitourworktoWordPress.org,wehavetodouble-checkourthemetomakesureit’svalidandmeetsallrequirementsofWordPress.org.Asthe_underscoresthemeisastartertheme,itcurrentlydoesn’tprovideeditorstyles.EditorstylesarethestylesfortheWordPresseditorinwpadmin(thebackend).Thepurposeofthesestylesistomatchthelookofpagesorpostsonfrontendwhentheendusergoestotheeditor.Forexample,ifwegotothehttp://localhost/topcat/markup-html-tags-and-formatting/post,we’llseethefollowingscreenshot:

Then,ifweopenthesamepostintheeditorinwpadmin,wegetthefollowing:

Fromtheprecedingscreenshot,wecanseethatthefontfamilyisnotthesame(step1),thefontcolorisnotthesame(step2),andtheblockquotestyling(customHTMLtagstyling)isnotapplied(step3).Tofixthisissue,wehavetodothefollowingtwothings:

1. Implementcustomeditorstyles,custom-editor-style.css.Inthisfile,wejusthavetoaddthiscode:

@importurl('style.css');

body{

background:nonerepeatscroll00#FFF;

font-family:"OpenSans",sans-serif;

line-height:14px;

margin:5px10px;

padding:5px;

}

Here,weareimportingourtheme’sstylesfirst,andthenwearemakingsurethatthebackgroundcoloriswhiteintheeditor(asfromourtheme’sstyles,thesilvercolorwouldbethedefaultoneandwedon’twantthatintheeditor).Wearemakingsureourfontfamilyisappliedtoo.

2. Addeditorstylesinfunctionsphp:

functiontopcat_add_editor_styles()

{

add_editor_style(array('custom-editor-style.css',

get_template_directory_uri().'/css/open-sans.css'));

}

add_action('after_setup_theme','topcat_add_editor_styles');

Here,weareaddingourcustomGooglefontsandhookingourcustomstylestothe

core.Thisistheresult:

ValidatingtheHTMLandCSScodeInorderforourthemetobeacceptedatWordPress.org,wehavetovalidateourHTMLandCSScode.

NoteForthisoperation,Istronglyrecommendthatyouusetwobrowsers[beingloggedinwithone—forexample,IE—andtesting(loggedout)withtheother,forexample,FF].AsyoustayloggedinintheFF,youmightseesomevalidationerrors/warningsfromtheWordPresstoolbar.Astheyarenotourerrors,theyshouldbeignored.

Forthispurpose,IamusingtheWebDeveloperpluginforFirefox,whichcanbedownloadedfromthislocation:https://addons.mozilla.org/en-US/firefox/addon/web-developer/.Whenyouinstallthisplugin,youwillgetaWebDevelopertoolbarjustundertheURL(address)bar:

ThegreatthingabouttheWebDeveloperpluginisthevalidationoptionsundertheToolssection.Ifyouwanttovalidatethecodewithouttheplugin,youwillhavetogotothewww.w3.orgwebsitemanually.WiththeWDplugin,youjustgototheToolssection,andyouwillbeabletochoosemanyoptions.MyfavoritetimesaversaretheValidateLocalCSSandValidateLocalHTMLoptions.Whenweclickontheseoptions,ourpagewillbevalidatedagainstw3.org’svalidator,andwewillseethefollowingresult:

TipYoumayhavemoreerrorsorlesserrorsthanIhave.

NoteTakealookattheresultscarefully.SomeoftheerrorsI’vehadwereactuallytheerrorsofaMetaSliderpluginandweshouldnotfixtheseaspluginsarenotpartofourtheme.

IwouldstronglyrecommendthatyougotroughasmanypostsasyoucaninordertovalidateHTMLandCSS.Ifwearecreatingacustompagetemplate,suchasfront-page.phpinthepreviouschapter,weshouldalsomakesurethattheyaretestedthoroughly.Weshouldnothaveanyerrorsorwarningsthere,althoughsomepostsusedeprecatedtags,likethisone:http://localhost/topcat/markup-html-tags-and-formatting/.Forthispost,I’vegotanumberoferrors,forexample,Theacronymelementisobsolete.Usetheabbrelementinstead.Theseerrorsshouldbeignored,asthesepostsarejustoldexamples.

Ialsostronglyrecommendthatyousubscribetothethemereviewteammailinglist,andifyouhaveanyquestions,feelfreetoaskthemthere.Thethemereviewteam’spageisavailablehere:https://make.wordpress.org/themes/.IhighlyrecommendthatyoufollowtheblogoftheAutomattic’sthemedivision,whichisavailableathttp://themeshaper.com/.

ValidatingtheJavaScriptcodeTovalidateanddebugtheJScode,IrecommendthatyouuseaConsoletabinFirebug.

NoteFirebugisanFFpluginthatreallyhelpswithdebuggingHTML,CSS,andJS.Itcanbedownloadedfromhttps://addons.mozilla.org/en-US/firefox/addon/firebug/.

ChromeusersshoulduseChromeDeveloperTools,whicharepartofChrome.

Toaccessbothofthesetools,youcanjustpressF12andtheywillshowuponyourpage.

Now,justchoosetheConsoletabinanyofthesetoolsandbrowsethetestpagesorposts.Ifthereisawarningoranerror,itwillappearhere.

ValidatingthePHPcodeThePHPcodeshouldbevalidallthetime,butsometimes,fixingerrorsandwarningsjusttakestoomuchofourtime.Displayingerrorsandwarningscansometimesbesodistractingthatwehavetodisabledisplayingthem.Ifwedothat,thenweshouldfixtheseproblemsatleastbeforewesubmitourcode,inthiscase,thethemetothepublicrepository.

DebuggingthesetupInordertoseetheerrors,weshouldaddthiscodetothewp-config.phpfilethatislocatedintherootfolderofourWordPressinstallation:

define('WP_DEBUG',true);

//EnableDebugloggingtothe/wp-content/debug.logfile

define('WP_DEBUG_LOG',true);

//Disabledisplayoferrorsandwarnings

define('WP_DEBUG_DISPLAY',true);

@ini_set('display_errors',1);

//UsedevversionsofcoreJSandCSSfiles(onlyneededifyouare

modifyingthesecorefiles)

define('SCRIPT_DEBUG',false);

TipNotethatwehavesetdisplayerrorstotrue:

@ini_set('display_errors',1);

NoteThissetting(displayingerrors)shouldonlybeappliedtoourlocal/devenvironment.Itshouldalwaysbedisabledonthestagingandproductionenvironments,asit’sunprofessionalforenduserstoseetheerrors.Atthesametime,itisalsoasecurityrisk,asweareprovidingthesysteminformationtoeverybody.

Moreinformationonsettingadebugenvironmentcanbefoundathttp://codex.wordpress.org/Debugging_in_WordPress.

Multiplewp-config.phpsetsAswewanttotestourcodeinasmanydifferentenvironmentsaswecan,Irecommendthatyoucodeandtestintwoenvironments:local(XAMPPonWindows)anddevserver(Linux/Centos).Becauseofthis,wehavetohavetwodifferentwp-config.phpsolutionsasourcredentialsaredifferentondifferentservers(andyoursshouldbetoo).Forthispurpose,Iamusingawordpress-multi-env-configsetupthatcanbedownloadedfromhttps://github.com/studio24/wordpress-multi-env-config.Althoughthisapproachhasanumberoffiles,it’sveryeasytosetup.Inoursetup,weshoulduse:

wp-config.php

wp-config.env.php

wp-config.development.php

wp-config.staging.php

Inwp-config.php,weshouldcommentout:

//DefineWordPressSiteURLsifnotalreadysetinconfigfiles

/*

if(!defined('WP_SITEURL')){

define('WP_SITEURL',$protocol.rtrim($hostname,'/'));

}

if(!defined('WP_HOME')){

define('WP_HOME',$protocol.rtrim($hostname,'/'));

}

*/

Inwp-config.env.php,weshouldsetupourenvironments:

switch($hostname){

case'localhost':

define('WP_ENV','development');

break;

case'topcat.mywebsite.com':

define('WP_ENV','staging');

break;

/*

case'www.domain.com':

default:

define('WP_ENV','production');

*/

}

Istronglyrecommendthatyousetupatleastadevelopmentandstagingenvironment;ifyouhaveasimilarsetup,whichmeansyouhaveatleastonelocalcomputerandserver.

Inwp-config.development.php,weshouldsetdatabasecredentials:

define('DB_NAME','your_db_name');

/**MySQLdatabaseusername*/

define('DB_USER','your_db_user_name');

/**MySQLdatabasepassword*/

define('DB_PASSWORD','your_db_password);

/**MySQLhostname*/

define('DB_HOST','localhost_or_your_servers_host_name');

Weshouldalsoputhereourdebuggingsettings,whichwejustmentioned.

Inwp-config.staging.php,weshouldhavethedatabaseanddebuggingsettings,andthat’sit.

Ifwehaveanerror/warningoranotice,weshouldseesomethinglikethis:

Let’sseethecodethatwascreatingaproblem:

echoedit_post_link(__('Edit','topcat'),'|&nbsp;&nbsp;<iclass="fa

fa-pencil-square-o"></i>&nbsp;&nbsp;<spanclass="edit">','</span>');

Theissueherewasthatwedidn’tputthetopcatvalueinsinglequotes.

Let’stakealookatthecomparisonamongnotices,errors,andwarnings.

Thefollowingdataisfoundathttp://php.net/manual/en/errorfunc.constants.php.

“Run-timenotices.Indicatethatthescriptencounteredsomethingthatcouldindicateanerror,butcouldalsohappeninthenormalcourseofrunningascript.”

Inourcase,wedidn’tusethesinglequotesandourcodedidn’tbreakthepage,butitwaspointedtousbythedebuggerthatweshouldfixthecode.

“Fatalrun-timeerrors.Theseindicateerrorsthatcannotberecoveredfrom,suchasamemoryallocationproblem.Executionofthescriptishalted.”

Thismeansthatwhenwehaveerrorsinourcode,itwillbreakthepage/script,andthatshouldbefixedimmediately.

“Run-timewarnings(non-fatalerrors).Executionofthescriptisnothalted.”

Thismeansthatwearebeingwarnedofanissuebutthatissueisnotbreakingthecode.

Weshoulddoourbesttoavoidhavinganyofthese(notices,errors,orwarnings)inourproduction-readycode.

Addingthereadme.txtfileEverythemethatissubmittedtotheWordPress.orgrepositoryshouldhavethereadme.txtfile.Inthatfile,weshouldputtheinformationregardingthetheme’scontributors/authorsandtagsthatdescribethemefeatures.

Thereadme.txtfileforourthemeisavailabletogetherwithotherfilesprovidedwiththischapterandalsoontheGitHubpageforourthemeathttps://github.com/dejanmarkovic/topcat-final.

Addingthescreenshot.pngfileThescreenshot.pngfileisanimportantfileaswecanprovidethescreenshotorsomeotherinformationregardingourthemethere(inourcase,weareprovidingthelogoforourtheme).Thescreenshot.pngfileshouldbeofthesize880x600pxor387x290px.Thescreenshot.pngfileforourthemeisavailabletogetherwithotherfilesprovidedwiththischapterandalsoontheGitHubpageforourtheme:https://github.com/dejanmarkovic/topcat-final.

Moreinforegardingscreenshot.pngcanbefoundathttps://codex.wordpress.org/Theme_Development#Screenshot.

RunningathemecheckpluginAswehavevalidatedallthecode,westillhaveonemorechecktodo,andthatistorunathemecheckplugin.Beforewerunit,wefirsthavetoenableit.Todothat,wehavetogoagaintoDeveloperpluginTools|DeveloperandclickonINACTIVE-ClicktoActivate;theresultis:

Then,weshouldrunthethemecheckbygoingtoAppearance|ThemeCheckandchoosingourthemefromthedrop-downmenuandclickingontheCheckit!option:

Afterthis,wewillgetaresultlikethis:

Aswecanseefromtheprecedingscreenshot,wehavetofixthethingsthataremarkedinred.Alltheseerrors/warningsareself-explanatory.ThefirsttwomentionthatweshouldtakeoutGitreferences(directoriesandfiles)beforewesubmitthecode,astheWordPress.orgrepositoryisusingsubversionandalsobecausewedon’twanttomixourownrepositorystuffwiththepublicrepository.

IalsostronglyrecommendthatyoulookintoRECOMMENDEDandINFO.

Afterwefixalltheerrors,weshouldgoandsubmitourthemehere:https://wordpress.org/themes/upload/.

IalsostronglyadvisethatyoureadthethemeHandbookhere:https://make.wordpress.org/themes/handbook/review/.

SummaryInthischapter,welearnedaboutapplyingtheeditorstyles;validatingtheHTML,CSS,JavaScriptandaPHPcode;runningthemeunittests;andsubmittingyourthemetoWordPress.org.Thisconcludesourbook.

Bynow,youhavelearnedhowtodeveloparesponsivethemeinWordPressandhowtosubmitthethemetoWordPress.org,followingtheWordPressCodex.

YouarenowreadyforyourownWordPressthemeadventureandthatcanbeworkingfortheagencybycreatingthethemes,startingyourownfreelancebusiness,ormaybestartingyourownWordPressthemedevelopmentcompany.Thechoiceisyours.Goodluckinyourfutureendeavors!

IndexA

archive.phptemplatemodifying/Modifyingarchive.php

Automattic’sthemedivisionURL/ValidatingtheHTMLandCSScode

BBitnami

about/InstallingandsettingupWordPressbodyclass

URL/Dealingwiththeheaderbreakpoints

about/Breakpointsbusiness-orientedtemplates

URL/Homepage

Ccode

polishing,beforesubmission/Polishingcodebeforesubmissioncomments

workingwith/Workingwithcommentsstyling/Stylingcommentsnavigating/Commentsnavigation

commentstitlestyling/Stylingcommentstitle

ContactUspageabout/TheContactUspage

content-single.phpfileanalyzing/Analyzingthecontent-single.phpfiletemplate,improving/Templateimprovementsposttemplate,modifying/Implementingchangestotheposttemplatepost’smetadata,styling/Stylingpost’smetadatacontentsection/Contentsection

ContentDeliveryNetwork(CDN)/Howtosetupfunctions.phpCSS

withmediaqueries,URL/AddingmediaqueriesCSScode

validating/ValidatingtheHTMLandCSScode

Ddebugenvironment

URL/DebuggingthesetupDeveloperplugin

URL/InstallingtheDeveloperplugindotsperinch(DPI)/Thescreendensitydynamic_sidebar()function

codexpage,URL/Sidebars

Eeditorstyles

applying/Applyingtheeditorstylesellipsissymbol/Excerptsemvalues

about/Theemandremvaluesexcerpts

about/ExcerptsURL/Excerpts

Ffatalrun-timeerrors/Multiplewp-config.phpsetsfeaturedimage

about/Featuredimagessettingup/Settingupafeaturedimageresizing/Resizingfeaturedimages

featuredimagesabout/Featuredimages

FirebugURL/ValidatingtheJavaScriptcode

flexibleimagesabout/Flexibleimagesandmedia

fluidgridsURL/Fluidgridsabout/Fluidgridsframework,positivefeatures/Frameworkspositivesframework,negativefeatures/Frameworksnegatives

FontAwesomeiconsURL/Problemsandsolutionswiththescreendensity

footerediting/Editingthefooter

functions.phpsettingup/Howtosetupfunctions.php

Ggallery

makingresponsive/Makingthegalleryresponsive

Hhardcropmode

URL/Settingupafeaturedimageheader

about/Dealingwiththeheaderhellip/Excerptshomepage

about/Homepagetemplate/Thehomepagetemplatestyles/Stylesforthehometemplatemakingresponsive/Makingourhomepageresponsive

HTMLcodevalidating/ValidatingtheHTMLandCSScode

Iimagecaptions

resizing/Imagecaptionsimagegalleries

about/Imagegalleries

JJavaScriptcode

validating/ValidatingtheJavaScriptcodeJetpack

about/Themesubfolders

LLayerSlider

URL/Sliderpluginlayout

makingcentered/Makingourlayoutcentered

Mmasonry

URL/Editingthefootermediaqueries

adding/Addingmediaqueriesmediaqueries,RWD

about/MediaqueriesURL/Mediaqueriesbreakpoints/Breakpoints

menucreating/Howtocreateamenuandmakeitresponsiveandaccessiblebasics/Menubasicsstyling/Stylingourmenuaccessibility/Howtomakeourmenuaccessibleresponsive/Howtomakeourmenuresponsive

ModernizrURL/Howtosetupfunctions.php

NNetBeans

URL/Choosingtherighttoolforourproject

OOpenSans

URL/Howtosetupfunctions.php

P404.phptemplate

modifying/Modifying404.phppageview(PV)

about/Analyzingthecontent-single.phpfilepagingnavigation

customizing/CustomizingthepagingnavigationPHPcode

validating/ValidatingthePHPcodePHPEclipse

URL/ChoosingtherighttoolforourprojectPhpStorm

URL/Choosingtherighttoolforourprojectpixelsperinch(PPI)/Thescreendensityposttemplate

modifying/Implementingchangestotheposttemplatemetadata,styling/Stylingpost’smetadata

postthumbnailsabout/Featuredimages

Rreadme.txtfile

referencelink/Addingthereadme.txtfileregister_sidebar()function

codexpage,URL/Sidebarsremvalues

about/Theemandremvaluesrun-timenotices/Multiplewp-config.phpsetsrun-timewarnings/Multiplewp-config.phpsetsRWD

concepts/TheconceptsofRWDViewport,controlling/ControllingViewportscaling/Scalingscreendensity,problems/Problemsandsolutionswiththescreendensityscreendensity,solutions/ProblemsandsolutionswiththescreendensityURL/TechniquesinRWDmediaqueries/Mediaqueriesfluidgrids/Fluidgridsflexibleimages/Flexibleimagesandmedia

Sscaling,RWD

about/Scalingscreendensity/Thescreendensity

screendensityabout/Thescreendensitysolutions/Problemsandsolutionswiththescreendensityproblems/Problemsandsolutionswiththescreendensity

screenshot.pngfilereferencelink/Addingthescreenshot.pngfile

search.phptemplatemodifying/Modifyingsearch.php

SearchEngineOptimization(SEO)about/Analyzingthecontent-single.phpfile

servicessectionabout/TheServicessection(listofservices)

setupdebugging/Debuggingthesetup

setupstyles.csssettingup/Howtosetupstyles.css

sidebarsabout/Sidebarsstyling/Stylingsidebars

singleposttemplatesanalyzing/Analyzingsingleposttemplates

sliderpluginabout/SliderpluginURL/Sliderplugin

stickypostsstyling/Stylingstickyposts

SuperfishjQuerypluginURL/Howtomakeourmenuaccessible

Ttags

displaying/Tagspostnavigation/Postnavigation

template,content-single.phpfileimproving/Templateimprovementsheader,improving/Headerimprovements

templatefilesabout/TemplatefilesThemeName/TemplatefilesThemeURI/TemplatefilesAuthor/TemplatefilesAuthorURI/TemplatefilesDescription/TemplatefilesVersion/TemplatefilesLicense/TemplatefilesLicenseURI/TemplatefilesTextDomain/TemplatefilesTags/Templatefilespagestructure/Thepagestructureoftemplatefiles

TGMPluginActivationURL/TheServicessection(listofservices)

themeURL/Settinguptheunderscoresthemeabout/WhatisaWordPresstheme?subfolders/Themesubfolders

themecheckpluginrunning/Runningathemecheckplugin

themetestingURL/InstallingtheWordPresstheme’sunittestdata

ThemeUnitTestDataURL/Contentsection

toolselecting,forproject/Choosingtherighttoolforourproject

Uunderscorestheme

about/SettinguptheunderscoresthemeURL/Settinguptheunderscorestheme

unittestdataURL/InstallingtheWordPresstheme’sunittestdata

Vvideos

workingwith/WorkingwithvideosViewport

controlling/ControllingViewport

WWAMPP

about/InstallingandsettingupWordPressWebDeveloperplugin

URL/ValidatingtheHTMLandCSScodewidgets

about/Widgetssidebars/Sidebarssidebars,styling/Stylingsidebarsfooter,editing/Editingthefooter

WordPressinstalling,URL/InstallingandsettingupWordPresspermalinks,setting/SettingWordPresspermalinkstheme/WhatisaWordPresstheme?templatefiles/Templatefilestheme,subfolders/Themesubfolders

WordPressCSSCodingStandardsURL/Choosingtherighttoolforourproject

WordPressenvironmentsettingup/SettinguptheWordPressenvironment,InstallingandsettingupWordPressinstalling/InstallingandsettingupWordPressunderscorestheme,settingup/SettinguptheunderscoresthemeDeveloperplugin,installing/InstallingtheDeveloperplugin

WordPressHTMLCodingStandardsURL/Choosingtherighttoolforourproject

WordPressJavaScriptCodingStandardsURL/Choosingtherighttoolforourproject

WordPressPHPCodingStandardsURL/Choosingtherighttoolforourproject

WordPresstemplatehierarchy,analyzing/TheWordPresstemplatehierarchyhierarchy,URL/TheWordPresstemplatehierarchy

WordPressthemeunittestdata,installing/InstallingtheWordPresstheme’sunittestdata

WorldWideWeb(WWW)about/Analyzingthecontent-single.phpfile

wp-config.phpsetsabout/Multiplewp-config.phpsetsreferencelink/Multiplewp-config.phpsetsreadme.txtfile,adding/Addingthereadme.txtfilescreenshot.pngfile,adding/Addingthescreenshot.pngfile

wpadmin

URL/TheServicessection(listofservices)WPTavernarticle

URL/TheServicessection(listofservices)

XXAMPP

about/InstallingandsettingupWordPress

Recommended