When sharing WordPress related code snippets, I can haz standards please?

Home » Blog » Code » When sharing WordPress related code snippets, I can haz standards please?

I love WordPress. Just absolutely love it. One of the things I love especially is how you can alter the output by adding just a small snippet of code. Turns out I”m not the only one who loves doing that because when you”re googling any given WordPress related subject, the pure amount of hits on Google can be overwhelming. I love how you can easily copy any of those snippets of code and put “em to use on your site.

But, I believe there”s something missing with all those snippets, at least in most cases. Two things: proper WordPress coding standards and inline documentation. Of those two articles on the Codex there are a few things that you should know about – whitespace, indentation & DocBlocks.

Here’s why. Not only does it make sense to adhere to WordPress coding standards when you’re building code that’s supposed to work with WordPress, but it also makes your code look good. Using function-level DocBlocks makes so much more sense when you think about it. When sharing your snippet – be it long or short – with tags like @author and @link, for example, make a few things a bit more obvious. Specifically, who the author is of the code, copyright information and the url explaining the snippet a bit more (most likely the article you have just written for that snippet). Code standards help especially in these two regards:

  1. Consistency between the code you your readers will have in their projects, and the code snippet you”re giving them – no odd coding styles to have to reformat.
  2. Consistency when different developers work on the same bit of code – no time spent having to learn someone else”s coding style.

Consider the following two examples:

Before:

After:

Mind you, this is not the most complicated function ever built and could thus probably do without the comments, but I wanted to get a point across here, remember? You”ll see I”ve also prefixed my functions properly, but I didn”t need to point that out to you guys, right? You all were obviously already doing that ;). I am by no means an expert on these matters, but I am inspired by Gary Jones – who helped write this post and whose expertise in this matter I hold in very high regard. Seeing him work on updating the code Genesis uses to the proper standards has inspired me to write this post.

So how about it? I would love to see sites like WPRecipes, WP-Snippets and WPBeginner adopt this style of writing code. I mean, isn”t this where the whole Code is Poetry starts? Also, consider pasting snippets on Github”s gists. Kinda like Pastebin, but cooler in my opinion. Your snippets are automagically turned into a Git repository. Making collaboration and code improving easier to do.

First name
This field is for validation purposes and should be left unchanged.

Automatically sent to your inbox, just like 🪄 

49 responses to “When sharing WordPress related code snippets, I can haz standards please?”

  1. BjornW Avatar

    I totally agree on the standards, but I would suggest to go beyond the WordPress coding standards 🙂

    Some suggestions:

    1. Make sure you use curly braces to delimit an if block.
    Leaving them out can cause lots of headaches especially in the long run when your adding or refactoring code.

    2. Add a statement to your docblock on the why and not just what your function does. Such as (just making it up..): ‘We use this extra class to distinguish guests from regular visitors to make them standout more so we can welcome them’ .

    3. Remove obvious comments. Comment the why, not the how since the code should tell you how it works when glancing over. So lose the comment on the return and the one one the logged in class. The docblock is sufficient.

    4. Check if your prepended function does not exists, by using the function_exists and only call the add_filter if your filter has been defined.

    See my edited gist here with the points above included: https://gist.github.com/1235290

    Thanks for bringing coding standards up, it’s an important part of a developer’s life 😉
    Btw have a look at the book Code Complete 2. IMHO the best book for all kinds of insightful tips & tricks on software development in general.

    1. Remkus Avatar

      Thanks for dropping by and comment Bjorn. I agree that the suggestions I do here are probably just a first step. It was particulary meant for all those short snippets thrown in posts everywhere.

      1. BjornW Avatar

        No problem. Thanks for starting the discussion. We can all learn a lot from each other, as well as from developers outside the WordPress or PHP world 🙂

    2. GaryJ Avatar

      1) Arguably, for consistency and avoiding headache’s, you could use { } at all times for if / foreach blocks, but there are so many times when it’s a simple one-liner amendment if the condition is true, that they are commonly left out. WP leaves them out (might even have examples on the CS page showing them left out?)
      2) That makes sense – and would be expandable in the long description of a DocBlock.
      3) Agreed.
      4) That’s a bit excessive, if it was going to be done for every single filter function. When someone is making a point of adding the snippet to their own project, then they’ll be copying both the add filter line AND the function definition which is the callback for it, so we know it exists. The use of function name prefix should ensure that it doesn’t already exist.

  2. Jean-Baptiste Jung Avatar

    The idea is good, but I do not plan to adopt that kind of coding on my sites for now. It is very verbose so I can’t imagine pasting this directly on your theme files. Most of my readers enjoy the “ready to use” kind of coding on WPRecipes.

    But I may be wrong, let’s see if I get some more feedback on this.

    1. Remkus Avatar

      Thanks for commenting Jean :). The thing of it though, I don’t think it’s verbose at all. Yes, you can loose the inline commenting, but the rest is simply just adhering to the WordPress way of working.

      All I am saying basically, is the we – as people sharing code – should lead by example.

  3. Filip Stefansson Avatar

    I’m ready to adopt parts of it for WP-Snippets. @link for instance is a great way to tell people where they can get help with the snippet if they have forgotten where they got it from(or if they found the snippet somewhere else).

    However, over at WP-Snippet a lot of the content is produced by the users, so it’s kinda up to them to provide the information like @link and @author if there is any.

    And like Jean said, it’s a bit verbose, and also looks a bit more intimidating for a WordPress newbie.

    1. Remkus Avatar

      Intimidating perhaps, but shouldn’t our goal be to teach and educate?

  4. Ryan Imel Avatar

    Yes. This.

    I approve.

    1. Remkus Avatar

      How could you not 😉

  5. […] You are here: Home > Links > Remkus de Vries on code snippet standards PermalinkRemkus de Vries on code snippet standardsYes, this please.Leave a commentTweet this post Preview the next update to the BuddyPress Welcome […]

  6. tyler Avatar

    I can’t be the only one wondering this.

    Remkus, how are you handling gist embeds here?

    1. Remkus Avatar

      I am using a plugin for that. I’ve set the width of the content in Settings/media and using an oEmbed plugin to display the Gists. More info here: http://firegoby.theta.ne.jp/wp/oembed-gist

  7. pixelDanny Avatar
    pixelDanny

    Is adding the add_* line above the docblock written in the WP standards anywhere? I see it done both ways in core so I’m just wondering which way is the correct one by the standards or does it not matter?

    1. Remkus Avatar

      To the best of my knowledge the new and proper way is on top.

    2. GaryJ Avatar
      GaryJ

      It’s not part of the WP standard, but it’s a sensible guideline that is used in the Genesis Framework – it allows the DocBlock to go immediately above the function so it is correctly associated, and having the add_* above that means all the key bits of information are together.

      If the add_* is put after the function is defined, then that critical information about where this function actually acts, might be several screen’s worth of scrolling away if it’s a particularly long function.

  8. Chip Bennett Avatar

    Great suggestion! I will certainly use proper documentation for all code snippets.

    Can I also suggest the @copyright and @license tags, to promote proper attribution and to facilitate modification and redistribution of GPL code?

    1. Remkus Avatar

      Absolutely Chip 🙂

  9. kevin Chard Avatar

    This is a very interesting idea and I will definitely be looking into this for my next update. Great article by the way,

    1. Remkus Avatar

      Thanks Kevin and welcome aboard 😉

  10. Otto Avatar

    No. Never.

    Snippets I post are not meant to be working code. They are not tested, not run, and not meant to be used as copy-pasta. Usually I type them on the fly, off the top of my head. They’re a demonstration only, to show somebody how to do something.

    Also, Github is the tool of the devil.

    So no, not going to happen. Not now, not ever. No.

    1. Remkus Avatar

      So.. You don’t think that the code you produce should be educational on standards as well?

      And Github a tool of the devil? Really? How do you figure that one? 🙂

      1. Otto Avatar

        Nope, I don’t. Standards come and go, ideas remain. Code is poetry, docblocks are make-work for people that can’t read code.

        And Github is fine, except that it uses Git. Hate Git. *Hate*. I have tried to use it multiple times, but the damn thing never works, makes no sense, and the underlying ideas strike me as stupid. So, no. Do not want.

        1. Mike Schinkel Avatar

          @Otto – Have you tried Mercurial yet? I couldn’t figure out Git either, but Mercurial just makes sense.

        2. Otto Avatar

          Haven’t tried mercurial yet, but as I was ranting about Git here in the lounge area in Louisville, somebody else sitting nearby told me to try mercurial too. So I’ll take a look.

        3. Mike Schinkel Avatar

          Create a free account on BitBucket.org to get your repositories (fyi, we have Sunrise there.) Get TortoiseHg as I think you are on Windows? And if you are using PhpStorm it has great Mercurial integration.

        4. Mike Schinkel Avatar

          @Otto – Also, this post makes lots of sense regarding Git vs. Mercurial:

          http://stevelosh.com/blog/2010/01/the-real-difference-between-mercurial-and-git/

          1. Remkus Avatar

            I don’t get why you guys don’t get Git. I mean, if I get Git…

            1. Otto Avatar

              Remkus: It’s not that I don’t get it. I fully understand it. I know how it is supposed to work (and how it utterly fails to work on Windows without much effort). I just don’t *like* it.

              The whole idea behind git is *bad*. IMO, of course. Git doesn’t do what I want it to do. What it does do offers me no advantages. Github does things in ways that I don’t want it to do them. And the things it claims to do don’t work.

              I don’t like Git because I understand it, not because I don’t.

            2. Remkus Avatar

              Got it ;). Personally, I love the speed and the ease to fork and collaborate. Especially via Github.

            3. Mike Schinkel Avatar

              @Remkus: Some people think “tomato” and other’s think “tomahto”…

        5. Otto Avatar

          I still don’t see how any of those are better than SVN for my own uses. Git and Hg don’t *add* anything that I want to use.

          Without any reason to switch, why switch? Doesn’t make sense. I’d rather spend time getting work done instead of fiddling with how I get that work done. Unless there’s some huge advantage, which I’m not seeing here, then I’ll just keep using what works.

    2. GaryJ Avatar
      GaryJ

      I guess it depends on what you think is the lowest ability of the potential somebodies who might be looking at your snippet.

      As an obviously prominent name in the WP community, I would hope that you realise that completely amateur coders will be looking at your snippets for how to do things (as well as competent coders).

      While the competent coders are there just looking at your logic, the amateurs are there looking at everything – logic, best practice, documentation, code standards, PHP functions that may be new to them, and everything else that will be moved across when they cope, paste and try to amend it to their own needs.

      If you want to show “somebody” how to do something, is it not better for everyone if you show them how to do it properly?

    3. Mike Schinkel Avatar

      @Otto (and @iain) – Depending on your audience for the code snippets, you may be doing a serious disservice by not testing snippets before posting. If you are posting on the wp-hackers list, okay, no problem; if we are on the list we can work through syntax errors.

      But if you are posting on the WordPress support forum populated by people who have no clue how to code in PHP, or in a blog post that Googling can bring anyone to see, your on-the-fly code will do nothing but frustrate most readers. It would be like you giving a language translation to another language that’s wrong; it could get someone who uses it in trouble. That’s why I have tested every one of the 388 answers I posted on WordPress Answers before I posted them. My 7 years as a programming instructor watching people who were trying to learn copy and paste code taught me how critical testing your example is to people’s ability to learn; if it doesn’t work from the start they are often dead in the water, especially where there is no programming instructor in the room they can ask for help.

      I’ll go further as to say if you want to be a good WordPress-centric webizen you have a responsibility to ensure your code is tested so as to keep the crap that can confuse people off the web. Not testing is just for benefit of your own convenience, nothing more. You’ll probably disagree with that assertion (you usually do 🙂 but I bet you’ll be in a small minority.

      1. Kirk Wight Avatar

        The only people with a responsibility for testing their posted code are those in a paid support position, and those purporting an authority in a subject (such as when writing a tutorial); everyone else is helping, and the onus of additional effort should fall on the one wanting help, rather than those helping.

        Sometimes those wanting to help only have a couple of minutes – isn’t it better that the untested code get posted, sending someone in the right direction, rather than, “urgh, I don’t have time to test this right now – screw it.”

        I’ll take Otto giving me an untested hint any day.

        1. Gary Jones (@GaryJ) Avatar

          But Otto does write some comprehensive and detailed tutorials, on tricky subjects – with few other tutorials around, it makes him / the tutorial the de facto authority. While arguably some of these tutorials are aimed at non-amateurs, it wouldn’t stop an amateur from trying to copy and paste code from it and get into a mess, if the snippets are not the best they could have been.

  11. iain Avatar
    iain

    I absolutely agree with @Otto
    Snippets are just peace of bytes(ideas) not working and tested code, if you were able to find it somewhere in the internet jungle, you know already what it is doing. And in the most time, you should modify that snippets to fit your needs and work for you.

    1. Remkus Avatar

      That’s just it. To you, me and Otto snippets might just be that. But people out there don’t view them as such. They view them as examples of how it’s done. And that’s why I’m suggesting we both use the proper formatting and DocBlock as per the guidelines. After all, if no one is showing the people out there what those standards are – and no, most of them won’t ever look into the actual core WordPress code – then how are we come to reach a point where those guidelines are actually used?

      With the risk of repeating myself here, but aren’t we supposed to lead by example when educating?

  12. WP Remote Control Avatar

    I always properly format and document my code… unless I don’t!

    Bad formatting out there is because people don’t use the right coding tools. I’ve been using NuSphere PhpEd for about 3 years now and if you hit Alt+F6 it formats the darn thing for you. If you type /** before of a function/method/property and hit enter, it prepares the documentation including arguments. Smart indents, stuff like that is a must today, especially for large projects.

    But when you use less ‘potent’ tools, the horror I see in code snippets is understandable. Takes a look at the WP core and it’ll hurt your eyes… Many probably code in notepad. I did like 7-8 years ago, but still formatted properly as it’s a lesson learned in 10+ years of C++ coding.

    PS: 5ubliminal here. I gratuitously used a product of mine in the name and URL of the comment to prove a point. There’s a lot of snippets in the footer of that site.

    PPS: Snippets should always be tested and working code. Less experienced people sometimes just need to plug them in and have them work. It looks really bad when your publicly exposed pseudo-code fails to work and people don’t understand it was just a ‘proof of concept’.

    PPPS: I accept replies with arguments but don’t reply with ‘Thanks for the comment (stopping by, etc…)’! NEVER. Only if you want to make sure I don’t comment again. I didn’t do you a favor. You’ll do me a favor freely hosting my opinion 😉
    (Introverts don’t have time for pleasantries.)

  13. […] work at Theme Force. Mine was oEmbed Gist, a plugin I like but have yet to try, that I found via Remkus de Vries.Subscribe to the show on iTunes, or directly to the RSS feed. As always you can send any emails […]

  14. Matthew Muro Avatar
    Matthew Muro

    Short snippets? Hmm, maybe not. Plugin code? Most definitely.

    1. Remkus Avatar

      Why not? Have you read the arguments here about leading by example?

  15. Chantal Avatar

    Don’t forget the CSS please! Especially when you are editing with multiple people. Comments of changes are really helpfull!

    1. Gary Jones (@GaryJ) Avatar

      Would that not be handled by version control commits, rather than documenting the changes inline? Especially for .css where documentation adds to the number of bytes that the ultimate end-user of the file ends-up downloading.

  16. […] expert, Remkus, also wrote a post about this some year ago. Wouldn’t it be nice if we all wrote our code as shown in the WordPress Coding Standards? The […]

  17. […] Realms founder, Remkus de Vries, pointed me to his article about standards and he suggested to use Gists to show code fragments. Gist is a part of Github which allows you to […]

  18. […] time ago, Remkus de Vries wrote a post on standards for code snippets. I’m a true fan of the WordPress Coding Standards, so hit me if any of my code snippets are […]

Leave a Reply

Your email address will not be published. Required fields are marked *