关闭

关闭

关闭

封号提示

内容

首页 Mastering WordPress.pdf

Mastering WordPress.pdf

Mastering WordPress.pdf

上传者: bill_mark 2012-07-17 评分 0 0 0 0 0 0 暂无简介 简介 举报

简介:本文档为《Mastering WordPresspdf》,可适用于IT/计算机领域,主题内容包含ImprintPublishedinNovemberSmashingMediaGmbH,Freiburg,GermanyCoverDesign:Ri符等。

ImprintPublishedinNovemberSmashingMediaGmbH,Freiburg,GermanyCoverDesign:RicardoGimenesEditing:AndrewRogerson,TalitaTelmaProofreading:AndrewLobo,IrisLjesnjaninReviewing:JeffStarrIdeaandConcept:SvenLennartz,VitalyFriedmanFoundedinSeptember,SmashingMagazinedeliversusefulandinnovativeinformationtoWebdesignersanddevelopersSmashingMagazine isawellrespectedinternationalonlinepublicationforprofessionalWebdesignersanddevelopers Ourmaingoal istosupporttheWebdesigncommunitywithusefulandvaluablearticlesandresources,writtenandcreatedbyexperienceddesignersanddevelopersISBN:Version:December,SmashingeBook#MasteringWordPressTableofContentsPreface!eDefinitiveGuideToWordPressHooksCustomFieldsHacksForWordPressPowerTipsForWordPressTemplateDevelopersAdvancedPowerTipsForWordPressTemplateDevelopersAdvancedPowerTipsforWordPressTemplateDevelopers:ReloadedTen!ingsEveryWordPressPluginDeveloperShouldKnowCreatePerfectEmailsForYourWordPressWebsiteWritingWordPressGuidesfortheAdvancedBeginnerAdvancedLayoutTemplatesInWordPress’ContentEditor!eAuthorsSmashingeBook#MasteringWordPressPrefaceWordPresshasmanyfacetstoshowforthosewholiketoexploreitspossibilitiesWellknownasafreesourceblogpublishingplatform,WordPressalsogainedpopularitybecauseofitsflexibilityanddevelopmentoptionsthroughplugins,hooksandcustomfields―justtonameafewIfyouarealreadyfamiliarwiththefundamentalsofWordPress,youmightbesearchingforspecificknowledgeinordertobecomeabetterexpertThisSmashingeBook#:MasteringWordPress,whichispackedwithexclusiveadvancedtechniques,isprobablywhatyouarelookingforAfterreadingthiseBook,youwillbeabletoimplementvarioushintswhichWordPresshastoofferforyourupcomingprojectsThiseBookcontainsarticleswhichbringstopicsthatwillhelpyouworkwithcustomfields,understandcodingwithhooks,maintainplugins,createemailsforyourwebsite,writeWordPressguidesandadministratelayoutcontenteditortemplatesThreewholechaptersaredestinedtoadviseyouwithpowertipsforWordPresstemplatedevelopersForinstance,youwillgettipswhichaddresscommonCMSimplementationchallengeswithoutplugindependenceandcoverahandfulofAPIcallsandintegrationwithPHPcodesAlso,thesetipsexplainhowtocustomizebasiccontentadministrationandaddfeaturestothepostandpageeditorinWordPressThearticleshavebeenpublishedonSmashingMagazineinand,andtheyhavebeencarefullyeditedandpreparedforthiseBookWehopethatyouwillfindthiseBookusefulandvaluableWearelookingforwardtoyourfeedbackonTwitterorviaourcontactformAndrewRogerson,SmashingeBookEditorSmashingeBook#MasteringWordPress!eDefinitiveGuideToWordPressHooksDanielPatakiIfyou’reintoWordPressdevelopment,youcan’tignorehooksforlongbeforeyouhavetodelveintothemheadonModifyingWordPresscorefilesisabignono,sowheneveryouwanttochangeexistingfunctionalityorcreatenewfunctionality,youwillhavetoturntohooksInthischapter,Iwouldliketodispelsomeoftheconfusionaroundhooks,becausenotonlyaretheythewaytocodeinWordPress,buttheyalsoteachusagreatdesignpatternfordevelopmentingeneralExplainingthisSmashingeBook#MasteringWordPressindepthwilltakeabitoftime,butbearwithme:bytheend,you’llbeabletojumblehooksaroundlikeaproWhyHooksExistIthinkthemostimportantstepingraspinghooksistounderstandtheneedforthemLet’screateaversionofaWordPressfunctionthatalreadyexists,andthenevolveitabitusingthe“hooksmindset”functiongetexcerpt($text,$length=){$excerpt=substr($text,$length)return$excerpt}Thisfunctiontakestwoparameters:astringandthelengthatwhichwewanttocutitWhathappensiftheuserwantsacharacterexcerptinsteadofacharacteroneTheyjustmodifytheparameterwhentheyusethefunctionNoproblemthereIfyouusethisfunctionalot,youwillnoticethattheparameterforthetextisusuallythepost’scontent,andthatyouusuallyusecharactersinsteadofthedefaultWouldn’titbeniceifyoucouldsetupnewdefaults,sothatyoudidn’thavetoaddthesameparametersoverandoveragainAlso,whathappensifyouwanttoaddsomemorecustomtexttotheendoftheexcerptThesearethekindsofproblemsthathookssolveLet’stakeaquicklookathowSmashingeBook#MasteringWordPressfunctiongetexcerpt($text,$length=){$length=applyfilters("excerptlength",$length)$excerpt=substr($text,$length)return$excerpt}Asyoucansee,thedefaultexcerptlengthisstill,butwe’vealsoappliedsomefilterstoitAfilterallowsyoutowriteafunctionthatmodifiesthevalueofsomething  inthiscase,theexcerpt’slengthThename(ortag)ofthisfilterisexcerptlength,andifnofunctionsareattachedtoit,thenitsvaluewillremainLet’sseehowwecannowusethistomodifythedefaultvaluefunctiongetexcerpt($text,$length=){$length=applyfilters("excerptlength")$excerpt=substr($text,$length)return$excerpt}functionmodifyexcerptlength(){return}addfilter("excerptlength","modifyexcerptlength")First,wehavedefinedafunctionthatdoesnothingbutreturnanumberAtthispoint,nothingisusingthefunction,solet’stellWordPressthatwewanttohookthisintotheexcerptlengthfilterSmashingeBook#MasteringWordPressWe’vesuccessfullychangedthedefaultexcerptlengthinWordPress,withouttouchingtheoriginalfunctionandwithoutevenhavingtowriteacustomexcerptfunctionThiswillbeextremelyuseful,becauseifyoualwayswantexcerptsthatarecharacterslong,justaddthisasafilterandthenyouwon’thavetospecifyiteverytimeSupposeyouwanttotackonsomemoretext,like“Readon,”totheendoftheexcerptWecouldmodifyouroriginalfunctiontoworkwithahookandthentieafunctiontothathook,likeso:functiongetexcerpt($text,$length=){$length=applyfilters("excerptlength")$excerpt=substr($text,$length)returnapplyfilters("excerptcontent",$excerpt)}functionmodifyexcerptcontent($excerpt){return$excerpt"Readon…"}addfilter("excerptcontent","modifyexcerptcontent")ThishookisplacedattheendofthefunctionandallowsustomodifyitsendresultThistime,we’vealsopassedtheoutputthatthefunctionwouldnormallyproduceasaparametertoourhookThefunctionthatwetietothishookwillreceivethisparameterAllwearedoinginourfunctionistakingtheoriginalcontentsof$excerptandappendingour“Readon”texttotheendButifwechoose,wecouldalsoreturnthetext“Clickthetitletoreadthisarticle,”whichwouldreplacethewholeexcerptSmashingeBook#MasteringWordPressWhileourexampleisabitredundant,sinceWordPressalreadyhasabetterfunction,hopefullyyou’vegottentogripswiththethinkingbehindhooksLet’slookmoreindepthatwhatgoesonwithfilters,actions,priorities,argumentsandtheotheryummyoptionsavailableFiltersAndActionsFiltersandactionsaretwotypesofhooksAsyousawintheprevioussection,afiltermodifiesthevalueofsomethingAnaction,ratherthanmodifyingsomething,callsanotherfunctiontorunbesideitAcommonlyusedactionhookiswpheadLet’sseehowthisworksYoumayhavenoticedafunctionatthebottomofyourwebsite’sheadsectionnamedwphead()Divingintothecodeofthisfunction,youcanseethatitcontainsacalltodoaction()Thisissimilartoapplyfilters()itmeanstorunallofthefunctionsthataretiedtothewpheadtagLet’sputacopyrightmetatagontopofeachpost’spagetotesthowthisworksaddaction("wphead","mycopyrightmeta")functionmycopyrightmeta(){if(issingular()){echo"<metaname="copyright"content="Me,">"}}!eWorkflowOfUsingHooksWhilehooksarebetterdocumentednowadays,theyhavebeenneglectedabituntilrecently,understandablysoYoucanfindsomegoodpointersintheSmashingeBook#MasteringWordPressCodex,butthebestthingtouseisAdamBrown’shookreference,andorlookatthesourcecodeSayyouwanttoaddfunctionalitytoyourblogthatnotifiesauthorswhentheirworkispublishedTodothis,youwouldneedtodosomethingwhenapostispublishedSo,let’strytofindahookrelatedtopublishingCanwetellwhetherweneedanactionorafilterSurewecan!Whenapostispublished,dowewanttomodifyitsdataordoacompletelyseparateactionTheansweristhelatter,sowe’llneedanactionLet’sgototheactionreferenceonAdamBrown’swebsite,andsearchfor“Publish”Thefirstthingyou’llfindisapppublishpostSoundsgoodlet’sclickonitThedetailspagedoesn’tgiveusalotofinfo(sometimesitdoes),soclickonthe“Viewhookinsource”linknexttoyourversionofWordPress(preferablythemostrecentversion)inthetableThiswebsiteshowsonlyasnippetofthefile,andunfortunatelythebeginningofthedocumentationiscutoff,soit’sdifficulttotellifthisiswhatweneedClickon“ViewcompletefileinSVN”togotothecompletefilesothatwecansearchforourhookInthefileIamviewing,thehookcanbefoundinthepublishposthook()function,which  accordingtothedocumentationaboveit  isa“hooktoschedulepingsandenclosureswhenapostispublished,”sothisisnotreallywhatweneedWithsomemoreresearchintheactionlist,you’llfindthepublishposthook,andthisiswhatweneedThefirstthingtodoiswritethefunctionthatsendsyouremailThisfunctionwillreceivethepost’sIDasanargument,soyoucanusethattopullsomeinformationintotheemailThesecondtaskistohookthisfunctionintotheactionLookatthefinishedcodebelowforthedetailsSmashingeBook#MasteringWordPressfunctionauthorNotification($postid){global$wpdb$post=getpost($postid)$author=getuserdata($post>postauthor)$message="Hi"$author>displayname",Yourpost,"$post>posttitle"hasjustbeenpublishedWelldone!"wpmail($author>useremail,"Yourarticleisonline",$message)}addaction('publishpost','authorNotification')NoticethatthefunctionwewroteisusableinitsownrightIthasaveryspecificfunction,butitisn’tonlyusabletogetherwithhooksyoucoulduseitinyourcodeanytimeIncaseyou’rewondering,wpmail()isanawesomemailerfunction  havealookattheWordPressCodexformoreinformationThisprocessmightseemabitcomplicatedatfirst,and,tobetotallyhonest,itdoesrequirebrowsingabitofdocumentationandsourcecodeatfirst,butasyoubecomemorecomfortablewiththissystem,yourtimespentresearchingwhattouseandwhentouseitwillbereducedtonearlynothingPrioritiesThethirdparameterwhenaddingyouractionsandfiltersisthepriorityThisbasicallydesignatestheorderinwhichattachedhooksshouldrunWehaven’tcoveredthissofar,butattachingmultiplefunctionstoahookis,ofcourse,possibleIfyouwantanemailtobesenttoanauthorwhentheirSmashingeBook#MasteringWordPresspostispublishedandtoalsoautomaticallytweetthepost,thesewouldbewrittenintwoseparatefunctions,eachtiedtothesametag(publishpost)PrioritiesdesignatewhichhookedfunctionshouldrunfirstThedefaultvalueis,butthiscanbechangedasneededPrioritiesusuallydon’tmakeahugedifference,thoughWhethertheemailissenttotheauthorbeforethearticleistweetedorviceversawon’tmakeahugedifferenceInrarercases,assigningaprioritycouldbeimportantYoumightwanttooverwritetheactionsofotherplugins(becareful,inthiscase),oryoumightwanttoenforceaspecificorderIrecentlyhadtooverwritefunctionalitywhenIwasaskedtooptimizeawebsiteThewebsitehadthreetofourplugins,withaboutnineJavaScriptfilesintotalInsteadofdisablingtheseplugins,ImademyownpluginthatoverwrotesomeoftheJavaScriptoutputtingfunctionalityofthosepluginsMypluginthenaddedtheminifiedJavaScriptcodeinonefileThisway,ifmypluginwasdeactivated,alloftheotherpluginswouldworkasexpectedSpecifyingArgumentsThefourthargumentwhenaddingfiltersandactionsspecifieshowmanyargumentsthehookedfunctiontakesThisisusuallydictatedbythehookitself,andyouwillneedtolookatthesourcetofindthisinformationAsyouknowfrombefore,yourfunctionsarerunwhentheyarecalledbyapplyfilters()ordoaction()Thesefunctionswillhavethetagastheirfirstargument(iethenameofthehookyouareplugginginto)andthenpassedargumentsassubsequentargumentsForexample,thefilterdefaultexcerptreceivestwoparameters,asseeninincludespostphpSmashingeBook#MasteringWordPress$post>postexcerpt=applyfilters('defaultexcerpt',$postexcerpt,$post)Theargumentsarewellnamed  $postexcerptand$post  soit’seasytoguessthatthefirstistheexcerpttextandthesecondisthepost’sobjectIfyouareunsure,itisusuallyeasiesteithertolookfurtherupinthesourceortooutputthemusingatestfunction(makesureyouaren’tinaproductionenvironment)functionmyfiltertest($postexcerpt,$post){echo"<pre>"printr($postexcerpt)printr($post)echo"<pre>"}addfilter("defaultexcerpt","myfiltertest")VariableHookNamesRememberwhenwelookedatthepublishpostactionInfact,thisisnotusedanymoreitwasrenamedinversionto{$newstatus}{$post>posttype}Withtheadventofcustomposttypes,itwasimportanttomakethesystemflexibleenoughforthemThisnewhooknowtakesanarbitrarystatusandposttype(theymustexistforittowork,obviously)Asaresult,publishpostisthecorrecttagtouse,butinreality,youwillbeusing{$newstatus}{$post>posttype}AfewofthesearearoundthenamingusuallysuggestswhatyouwillneedtonametheactionSmashingeBook#MasteringWordPressWhoIsHookedOnWhoTofindoutwhichfunctionhooksintowhat,youcanusetheneatscriptbelowUsethisfunctionwithoutargumentstogetamassivelistofeverything,oraddatagtogetfunctionsthatarehookedtothatonetagThisisagreatonetokeepinyourdebuggingtoolbelt!function listhookedfunctions($tag=false){global $wpfilterif ($tag) {$hook$tag=$wpfilter$tagif (!isarray($hook$tag)) {triggererror("Nothing found for '$tag' hook", EUSERWARNING)return}}else {$hook=$wpfilterksort($hook)}echo '<pre>'foreach($hook as $tag => $priority){echo "<br ><strong>$tag<strong><br >"ksort($priority)foreach($priority as $priority => $function){echo $priorityforeach($function as $name => $properties) echo "t$name<br >"}}echo '<pre>'return}SmashingeBook#MasteringWordPressCreatingYourOwnHooksAtonofhooksarebuiltintoWordPress,butnothingisstoppingyoufromcreatingyourownusingthefunctionswe’velookedatsofarThismaybebeneficialifyouarebuildingacomplexpluginintendedforwidereleaseitwillmakeyourandotherdevelopers’jobsaloteasier!Intheexamplebelow,Ihaveassumedwearebuildingfunctionalityforuserstopostshortblurbsonyourwebsite’swallWe’llwriteafunctiontocheckforprofanityandhookittothefunctionthataddstheblurbstothewallLookatthefullcodebelowTheexplanationensuesfunctionpostblurb($userid,$text){$text=applyfilters("blurbtext",$text)if(!empty($text)){$wpdb>insert('mywall',array("userid"=>$userid,"date"=>date("YmdH:i:s"),"text"=>$text),array("d",s","s"))}}functionprofanityfilter($text){$textelements=explode("",$text)$profanity=array("badword","naughtyword","inappropriatelanguage")if(arrayintersect($profanity,$textelements)){returnfalse}else{return$text}}SmashingeBook#MasteringWordPressaddfilter("blurbtext","profanityfilter")ThefirstthinginthecodeisthedesignationofthefunctionthataddstheblurbNoticethatIincludedtheapplyfilters()function,whichwewillusetoaddourprofanitycheckNextupisourprofanitycheckingfunctionThischecksthetextasitsargumentagainstanarrayofknownnaughtywordsByusingarrayintersect(),welookforarrayelementsthatareinbotharrays  thesewouldbetheprofanewordsIfthereareany,thenreturnfalseotherwise,returntheoriginaltextThelastpartactuallyhooksthisfunctionintoourblurbaddingscriptNowotherdeveloperscanhooktheirownfunctionsintoourscriptTheycouldbuildaspamfilterorabetterprofanityfilterAlltheywouldneedtodoishookitinMixingAndMatchingThebeautyofthissystemisthatitusesfunctionsforeverythingIfyouwant,youcanusethesameprofanityfilterforotherpurposes,evenoutsideofWordPress,becauseitisjustasimplefunctionAlreadyhaveaprofanityfilterfunctionCopyandpasteitinallyou’llneedtodoisaddtheonelinethatactuallyhooksitinThismakesfunctionseasilyreusableinvarioussituations,givingyoumoreflexibilityandsavingyousometimeaswell!at’sAllHopefully,younowfullyunderstandhowthehookssystemworksinWordPressItcontainsanimportantpatternthatmanyofuscoulduseevenoutsideofWordPressSmashingeBook#MasteringWordPressThisisoneaspectofWordPressthatdoestakesometimegettingusedtoifyou’recomingtoitwithoutanypreviousknowledgeThebiggestproblemisusuallythatpeoplegetlostinallofthefiltersavailableorinfindingtheirargumentsandsoon,butwithsomepatiencethiscanbeovercomeeasilyJuststartusingthem,andyou’llbeamasterinnotime!SmashingeBook#MasteringWordPressCustomFieldsHacksForWordPressJeanBaptisteJungTheincredibleflexibilityofWordPressisoneofthebiggestreasonsforitspopularityamongbloggersworldwideCustomfieldsinparticular,whichletuserscreatevariablesandaddcustomvaluestothem,areoneofthereasonsforWordPress’flexibilityInthischapter,we’vecompiledalistofusefulthingsthatyoucandowithcustomfieldsinWordPressAmongthemaresettingexpirationtimeforposts,defininghowblogpostsaredisplayedonthefrontpage,displayingyourmoodormusic,embeddingcustomCSSstyles,disablingsearchengineindexingforindividualposts,insertinga“Diggthis”buttononlywhenyouneeditand,ofcourse,displayingthumbnailsnexttoyourpostsSetAnExpirationTimeForPostsTheproblemSometimes(forexample,ifyou’rerunningacontest),youwanttobeabletop

用户评论(0)

0/200

精彩专题

上传我的资料

每篇奖励 +2积分

资料评价:

/33
仅支持在线阅读

意见
反馈

立即扫码关注

爱问共享资料微信公众号

返回
顶部