Are You A Hack Developer?

I made a short comment while I was semi-drunk last night on a post in reddit’s r/personalfinance about my wake up call as a shitty developer.  I started getting a lot of “hits close to home” comments and private messages.  Surprised me, I thought it was just going to get buried.

I guess there’s a lot of us out there.  Those of us that taught ourselves to code.  Those of us that made/make a living developing by themselves.  I figured I should share my story.

I’ve freelanced since I was 18.  I went to undergrad for interactive design (no coding, all flash) and graduate school for Marketing and Management.  I suck at both.

I got a job out of grad school as the Webmaster for a large hospital.  After that I got $180k funding for a start up idea I had and I tried to build it by myself over the course of a year and a half… it failed.  That’s a whole different story in itself.  Then I got a job as a Webmaster for a University.

Notice a trend here? Coding solo.  No code reviews.  No requirements or standards.

The title “Webmaster” is so antiquated and seems to relate to public or government institutions.  It also means coding alone, typically.

Getting By

I had no problem with my work or how I did it.  People needed shit built or managed and I did that.  When I delivered it, it worked.  But it also broke… all. the. time.

I’d patch shitty code with more shitty code.  The source was disgusting.  But I had no idea, I figured it was fine.  Classes? git? An IDE? Local environment? Who needs that shit, I’m building stuff just fine in Notepad++ and a couple huge files with intense amounts of logic mixed into views and db calls.  Hey, they shared a header file and sometimes a footer.  I know how to INSERT and SELECT and UPDATE… who fucking needs a JOIN statement when I can just run 10 queries and a dozen for loops and nested if statements to get the data I need.

I Was Getting Paid

The hospital gig was $58k right out of grad school and rose to $70k over three years with insane benefits.  The University job was shit pay but the workload was so ridiculously light and the benefits were phenomenal.  I had so much time to freelance.

I regularly pulled in between 70-90k throughout my 20s.  Why would I think I needed to learn how to do things better?  I could pick up new languages or frameworks with ease.  I was writing VB.NET and action script for the first five years, then oh, everyone’s using WordPress now?  It’s php? Ok, I’ll learn php.

That was easy.  I mean, coding languages are all basically the same on the web, or so I thought.  You have variables, functions, you get the request variables, you go in and out of a database and you display your shit in html with, in my case, some nasty fucking javascript and inline styles.

WordPress was super easy.  Grab a free theme and some plugins.  Then I could just edit the plugin files to do what I wanted or hack through a themes templates and css.  Updates? Who needs updates, it works as is.

Chris Wiegman

Obviously, now, this is a problem.  A big one.  I hadn’t grown as a developer in ten years.  I was building sites that were getting hacked like crazy.  I always found a way to blame it on the client or WordPress and never myself.  Clients believed me, I kept getting paid, but the nightmare situation of all going to hell was building up and I had no idea.

I decided wearing nice clothes to an office 35 minutes away every day just wasn’t for me.  I was losing my mind, honestly.  I’m extremely ADD and terrible at corporate environments.  Then I met a guy.  A WordPress guy.

My favorite pub in town is a craft beer bar called Mr. Beery’s.  I met a guy there a couple years ago and we became friends.  Found out we were both primarily working in WordPress and started talking about it a lot.  He told me how he worked from home full time.  I was like… that is what I want.  No, that’s what I need.

Later on I found out Chris built a huge plugin and sold it.  iThemes Security is his work.  My mind was blown.  Dude who built one of, if not the biggest security plugins on WordPress, possibly on the web since WP is now 27% of it.  And he was my freaking neighbor.

I had talked myself up, very confidently to Chris. He told me to apply somewhere and that there are tons of agencies out there that hire remote WordPress devs.  So I submitted an application to 10up, the biggest WordPress agency out there (I think).

I was feeling good about it.  I’m a very personable guy.  Very social, good communicator and wrote great cover letters.  I got hit up by 10up almost instantly.  They wanted an interview.  OH MY GOD IT’S COMING TRUE!

The Interview

I had a video chat with a lovely lady from 10up.  We had a  great time.  Talking about culture, my family, my background, all my amazing websites I’ve built and so on.  They hit me up asking for another interview.  At this point, I felt like I had this job in the bag.

We had a second interview.  Nailed it again.  Now came the code review.

I was supposed to submit some code samples to them.  They said send them links to git repos or just some files. I decided on files because I had no clue what git even did.

So I zipped up some stuff I’d built and sent it over.  Kept telling my wife how excited I was, job was totally mine.

First reply was “hey, do you have any more code you could send over?” I didn’t know why they’d ask that.  I sent my best stuff.  So I scraped together some more code and sent it.

Then I got the email along these lines, “hey, we don’t think your coding level is where it should be for this position.  We really like you and would love to have you at our company so please feel free to apply again when you level up.”

Motivation

I was depressed man.  That shit stung more than any break up, more than any shut down, more than anything.  I was distraught.  I felt like the biggest loser, faker on the planet.  I knew nothing.  My code was shit.  I should probably just switch careers.

But Chris wouldn’t let me stay down.  He pushed me.  He told me I could level up.  He said explicitly, “let’s level you up.” I’d never had a mentor before, he didn’t even realize he was one.

Having someone believe in you is a big deal.  I didn’t know that but now I was experiencing it.

I gathered a serious amount of motivation.  First goal: build a plugin for WordPress that can be released in the public repo.  You have to submit it for review, so your code has to be at least somewhat decent to get in.

Leveling Up

I made a people lister.  It had a custom post type for people.  You put in their name and some meta data like a position at a company.  You could sort them then use a short code to display the listing in a nicely laid out format.

I look back at that code now and it’s shit, but man, it was LIGHTYEARS better than anything I had written before and it got into the repo.  I leveled up.

Next level was using a proper IDE, I got php storm and used it and only it.  I setup a git account and started making repos for every project.  I installed vagrant and VVV as a local environment.

I forced myself out of WordPress for a couple projects and learned about system architecture, routing, autoloading and so on.  I was asked to contribute to a project with some new friends I’d made in the WordPress world so I had to learn about npm and gulp and sass.

I threw myself at any opportunity to build with others.  I truly believe that was the #1 thing that has got me to where I am.

I learned NativeScript for building mobile apps.  It’s such a small community right now that when I started blogging on things I learned while developing in it I got a ton of traffic.  I still do get loads of google traffic to NativeScript articles.  I was discovering first time solutions and got indexed early.

I started applying to speak at WordCamps and surprisingly, I was accepted to five in 2016.  That was an amazing experience.

Don’t Give Up

As I grew confident in my skills and began building a small name for myself in the WordPress community I decided to give the job hunt another try.  I was told the Modern Tribe (Update September 2017: I now work full time for Tribe, just hit 90 days with them!!) was hiring.  I redid the resume, I had this website up by then and I had a much better code catalog.

They contacted me fast and setup an interview.  I interviewed with two different people.  A culture person, then a code person.  Both interviews were awesome and they really enjoyed me as a person.

Code review was fine, they said I was moving to the final stage and they were going to give me a small 8 hour freelance project.  I was pumped, even more than last time.  I had confidence this time that was legit and founded.

I finished the project and handed it in.  A week later I had a video call with them.

I didn’t get it.  They were upset as they really wanted me but they didn’t want to set me up for failure.  They hiring a senior level developer that really needed to be a system architect at the same time.  I just wasn’t there yet.

I wanted to give up, but again… I refocused and stayed motivated.

Still Growing

So here I am now, working from home.  Got a killer full time gig for a WordPress agency based out of Toronto.  I love my team and truly love my job.  I barely freelance anymore, just a couple long term clients that I help out a few hours a month for some extra cash.

I’m a good developer now and I can say that with earned confidence.  I still have a lot to learn and I’m leveling up regularly.  I want to be the best.  I want to write the best code.  The motivation has gone no where.

Are You A Hack?

I wrote this to hopefully motivate some others out there that were the same as me.  I’m 33 now and try not to think about it, but I probably could’ve been doing this 7 or 8 years ago if I’d started the process.  But I’m happy where I am and you can be too.

P.S. If you want a code review, hit me up.  Ready to pay it forward!

Yoast Primary Category Endpoint for the WP REST API

I had a special case today where I needed to pull in posts specifically from a Yoast SEO Plugin‘s primary category.  Yoast SEO allows you to set a single, primary category for a post in WordPress.  This is an awesome feature and very useful.

A site I’m building right now uses the API to pull in the latest articles of a category in a big drop down hero navigation system.  The thing is, just pulling from a category gets a lot of the same articles when clicking around the different category options.  We wanted to pull by primary category so each click gives a unique set of posts that are very relevant to the category option.

The Struggle

There may be a super simple way to do this already but I was seriously struggling googling for the answer.  I’ve done some extending of the WP REST API but I’m still a novice so I was hoping to avoid it.  But glad I didn’t because I learned a lot and I made a cool thing!

I couldn’t find a function in Yoast that pulled post IDs or anything based on a primary category.  I needed to figure out how they assigned this.  I dug through the database and found a post meta with the key ‘_yoast_wpseo_primary_category.’  This is it, this is what I’ll use to build my end point.

The Code

First we need to register our endpoint/route.  I prefer building things in classes so I created a class:

<?php
class Rest_Api_Posts_By_Primary_Category {}

I register the endpoint in the __construct() as so:

https://gist.github.com/ChrisFlannagan/a6f63a02ea16268a25bc5d386e9ac63a#file-primary-cat-part-1-php

SITE_PREFIX is something I set in my theme’s functions.php file.  You need a namespace here so make it unique based on your plugin or theme or site in general.

The callback function is where the magic happens.  In get_posts_by_primary_cat( $data ) we do a simple WP_Query that makes use of the meta_query ability.  The thing is, I need the children of categories too.  Here’s an example similar to what I’m dealing with.

Let’s say we have three categories and these categories are what we see in our navigation menu: Math, Reading, History

Then those categories each have two children: ###-Lessons, ###-Research

So our final category structure looks like

Math
 – Math-Lessons
 – Math-Research
Reading
 – Reading-Lessons
 – Reading-Research
History
 – History-Lessons
 – History-Research

If someone clicks Reading I want to load all posts that have a primary category of Reading, Reading-Lessons or Reading-Research… so I need the children.

In the function below you can see I run get_categories on the selected category withe parent argument assigned.  This gets me all the children.  I just need their ids and I need them in string format so I run a quick foreach loop.   I make sure to add the original parent id back to the new array too.  Then I run the WP_Query.

https://gist.github.com/ChrisFlannagan/a6f63a02ea16268a25bc5d386e9ac63a#file-primary-cat-part-2-php

At this point you could just return $posts->posts but I needed the featured image and only a few of the pieces like title, time and a link.  So I built out what I need and return that.

Conclusion

Now to use this we simply visit http://yoursite.com/wp-json/SITE_PREFIX/v1/yoastprimary/##-catid-## and replace ##-catid-## with the actual category number.  I could’ve just made this a static class now that I think about it but whatever, you must remember to initiate it to work.  So in your functions.php of the theme or somewhere in your plugin call $rest_api_primary_cat = new Rest_Api_Posts_By_Primary_Category();

This was easy to parse in my javascript and is running great.  Hope it helps someone! Here’s the full code:

https://gist.github.com/ChrisFlannagan/a6f63a02ea16268a25bc5d386e9ac63a#file-primary-cat-php

Remove the +Add New Category / Custom Taxonomy Link in WordPress

This post is more about custom taxonomies than it is adjusting category capabilities, but it’s  probably resolved the same way.   So i mention how I’d go about it after I explain what I’ve been doing.

I have a theme that has a custom post type called Members.  These members need to be attached to posts at the authors choice.  For instance, an admin is adding a new blog post.  There are three posts in the custom post type Members: John, Jack & Jill.  This post should be attached a Jill taxonomy/category.

I could solve this with a custom taxonomy, but I want the term options to be only what posts are made in Members.  Problem is, I don’t want the admin to be able to add new terms here.  So that big +Add New Category/Member link has to go.

I could do it with CSS but then someone smart could get around that.  I need it done server side.

Removing the Functionality

As far as I can tell there’s no filter to hook into and remove that feature.  It’s not an argument when registering a taxonomy so you can’t just re-register category or set it when creating a custom tax.

What you can set is what users are allowed to edit/add terms.  The long route would be creating a custom user role and assigning only them.  But I thought to myself, what would WordPress do if I just used a user role that doesn’t exists?  So I did this:

https://gist.github.com/ChrisFlannagan/4cd3bfd0e853cda3d3f7898c59428ac2

I set edit_terms and manage_terms to ‘god’ and voila! The option is gone!

Add Variation To Cart in WooCommerce: Don’t Forget The Attributes!

The point of this post is to help others that are having a problem dynamically adding a variation of a product (or subscription product in my case) to cart.  I get to that at the bottom of this post if you want to skip the story.

The Problem

I have a pretty high up there client in the box subscription world.  I’ve been brought in to do some WooCommerce functionality with WooSubscriptions and everything else involved.

The checkout process is pretty customized.  We have a page that displays all the attributes available for the subscription variable product.  There’s a bunch of fancy selection boxes and lists and gift inputs and so on.  It’s front end heavy but communicates with a custom endpoint through the REST API that I wrote to add the item to cart.  Problem is, the sub form doesn’t give me a variation id, only the variable subscription product id and all the selected attribute values.

Finding the Variation

The first step is to find which variation they’ve selected.  Someone long before me went through the rigorous process of creating some 50-60 variations of this variable subscription product to match all the different options a user could select.

So I use a WP_Query search the for any post id that has all the meta_key/meta_value matches and select it.  It was a bit of a pain to figure out the best process here but this works.

Adding the Variation to Cart

Took me a few to find the right parameters for adding a variation to cart.  Now that I had the post id of that variation it looked pretty simple from what I found online:

$added = WC()->cart->add_to_cart( $query->post->post_parent, 1, $data['variation_id'] );

This did the trick.  Since I used a WP_Query to get the post I could select the parent (which is the main subscription variable product) needed for first parameter.  Then the quantity, then the variation id.  Which was $query->post->ID but I assigned it to some data my API was returning.

The user checked out and the variation was in the order.  A day after pushing this code the site owner asked where the order details went.  Turns out it original showed the selected attributes in the admin order panel.  I spent a couple hours figuring this out, which I feel dumb now, but going in blind what can you expect.

You have a fourth parameter you can for $variation_data.  This gives it the attribute love it wants and adds it to the order.  Why woo doesn’t just do this automatically if a variation is added? Beats me.  But here’s how you do it using a nice woo provided function for variations.

$added = WC()->cart->add_to_cart( $query->post->post_parent, 1, $data['variation_id'], wc_get_product_variation_attributes( $data['variation_id'] ) );

New Job, New Kid

Woke up this morning and saw a tweet @ me while heading out to work.

I accepted a position at FlowPress a couple weeks ago.  I start on November 7th and I’m crazy excited.  My dream the past couple of years has been to work for a WordPress agency remote.  My reasons:

  1. I love coding WordPress.  But in every job I’ve had I’ve been in charge or tasked in some way with digital marketing, banners and graphics, fixing co-worker computers and in the smaller companies helping move desks and furniture around.  I’m sick of this, I want to do what I’m good at and what I’m dedicated to.
  2. Why do all these jobs require me to come to an office? And why do I have to dress in a certain way? I sit in meetings that have nothing to do with me then I sit in my office and almost no one talks to me.  The times people do they could easily just call, email, text or smoke signal.  There is NO reason for me to drive some where every day.  Over the past three years I’ve been driving anywhere from 30 to 45 minutes each way to go sit in an office for no reason.

I work best when there’s no frivolous B.S. I have to deal with like a commute or dumb meetings about new rules surrounding the use of the office kitchen or what items should be in gift bags at a fund raising event… yes, these are actual meetings I’ve had at previous jobs as the WEBMASTER.

FlowPress

I’ll be a developer/engineer at FlowPress working strictly with WordPress systems.  This is my passion.  I cannot wait to start and look forward to being part of that team and growing with the company.

I’ve been chatting it up on Slack and made it to a couple of stand up meetings already.  I feel like I’m meshing well and will be a good fit.  We may actually be flying up to Toronto to hang with the team in person mid December!

August Knight

My start date was kind of floating.  My wife was due November 14th to bring our son into the world.  August Knight Flannagan decided to come three and a half weeks early and was born on October 21st at 8:51am.

While it was scary having a premature baby, he is completely healthy and so is momma.  I’m overjoyed to have him in our home and it’s cool he and I have birthdays only three days apart.

My wife had to go back into the hospital for 24 hours the day after we got home due to high blood pressure.  So I got to take care of him alone, overnight.  I was a nervous wreck but stayed strong and capable and we had an uneventful day/night together.

Perfect Timing

Honestly, his timing was perfect.  Now I’m able to start sooner with FlowPress.  We got our regiment down at home and I’ll be able to focus 100% when I start on Monday.

I was worried.  No one likes to start a new job with a bunch of unknowns being worked through at home.  If he came right as I was beginning my work with FlowPress I’d have been pulled away every day or two for a doctor appointment or to spend 24 hours alone with him while my wife was in the hospital or while figuring out sleeping patterns and so on.  The burden of dealing with that while starting this new venture is now gone!

So What’s Up

I’ll be dedicating myself to the new gig but keeping myself out there in the WordPress world as a contributor as well.  You will still find me blogging here and at The WP Crowd and I’m gonna try to up my Twitter game a bit.  I mean, I’ve been on there a year now, I should really start using it regularly.

WooCommerce Buy One Get One Half Off (50% Off) Hook/Plugin – IN PROGRESS

We have a deal coming up for all of November at my work.  Buy one, get one half off.  There’s no way to do this in vanilla WooCommerce.  I looked at Dynamic Pricing and it didn’t seem to offer this ability and if it did it was crazy complicated.  I looked at some other plugins out there and found one that may work but it was pro version only and I didn’t want to pay to find out.

I figured this is pretty straight forward need so why not write up a function real fast.  Here’s my train of thought followed by a code example.  This is only a proof of concept and I still need to add – price limits (items must be over a certain price for this to work), category limits and the ability to apply this more than once to an order.  But as of now it will take the second highest priced item and give it a 50% discount.  If you have two of the same item as the highest price it will discount the amount to make it the same as taking 50% off just one of the items.

First we need to hook into woocommerce_before_calculate_totals.  This way we can change the price on the cart and on the checkout.

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $cart_object ) {

Then I set variables for highest price, quantity of that item, a counter so we know if the shopper has more than 1 item in our discount range (for future use with pricing bottoms) and next highest price item.

$highest_price_id = 0;
$highest_price_quantity = 0;
$cnt = 0;
$highest_price = 0;
$next_highest_price_id = 0;
$next_highest_price = 0;

I need to optimize this, there should be no need for looping the cart twice but in a hurry to prove the concept works this morning and get something ready for our promo I did it this way.  I loop through the cart and gather all my data: highest priced item, quantity and so on.  Then we loop the contents again and reduce price where needed.

foreach ( $cart_object->cart_contents as $key => $value ) {
   if( $value['data']->price > $highest_price ) {
      $highest_price = $value['data']->price;
      $highest_price_id = $value['product_id'];
      $highest_price_quantity = $value['quantity'];
      $cnt++;
   }

   if( $value['data']->price < $highest_price && $value['data']->price > $next_highest_price ) {
      $next_highest_price = $value['data']->price;
      $next_highest_price_id = $value['product_id'];
      $cnt++;
   }
}

The final loop we first check if:

  1. Highest priced item is more than 1 quantity and we are on it in the loop
  2. There’s no other item that’s considered the second highest price.  If there is, we want to discount that and not one of the highest priced items.
  3. If any of that fails then we check if this is the next highest priced item and run our discount here
foreach ( $cart_object->cart_contents as $key => $value ) {
   if ( $highest_price_quantity > 1 && $value['product_id'] === $highest_price_id && $next_highest_price === 0 ) {
      $value['data']->price = $value['data']->price - ( $value['data']->price / $value['quantity'] ) * .5;
   } elseif ( $value['product_id'] === $next_highest_price_id && $cnt > 1 ) {
      $value['data']->price = $value['data']->price - ( $value['data']->price / $value['quantity'] ) * .5;
   }
}

The discount is based on quantity.  If someone has two of the same $99 item we don’t want to make them both $48.  We want to discount just the first item but I’m not sure if that’s even doable.  We could generate a coupon or some other more complicated options but I went with the simple approach.  Let’s take the quantity, divide the price by that (so we have two $99 items, 99/2 is $48) then take 50% of that and subtract it from the price.  Each item will have 25% subtracted basically and add up to 50% total discount on 2 items.

I’ve been testing this and it seems to be working.  I JUST put this together though so needs a lot more testing to make sure it’s working correctly.

https://gist.github.com/ChrisFlannagan/0d2010c49f582d5d89fa6f9740bf5703

Tracking Conversions in WooCommerce with Simple Link Codes the Easy Way & More

woocommerce-tracking-code-plugin-simpleI wrote about this as I was building it out.  It’s evolved a bit and is now on the WordPress Plugin Repository.

https://wordpress.org/plugins/quick-tracking-conversions-for-woocommerce/

It’s simple.  You setup codes you want to track for conversions in WooCommerce.  If you have an email blast coming up then just create a code for it and attach that code to the end of all links in the email blast.  This works for affiliates, whatever.

The link looks like this: https://whoischris.com/?qtc_woo_tracking_code=testcode

Of course you can replace “testcode” with anything you want and have as many tracking codes as you’d like.  Then in the admin, you input the code you want to see the results of.  You get a total and # of conversions.  I have every intention of adding more in depth analytics but this is a proof of concept.

Passwords to Conversions Analytics

What I encountered the following week at work presented a new problem.  We are starting a site for retailers and professionals in our industry.  We sell a specialized tool only to licensed professionals and we want them to be able to carry our consumer product on their shelves, so they need to be able to buy at a discounted, bulk price.

Fortunately this site is on its own domain and I can make the functionality global.  So here’s what I needed to happen:

  • All shopping functionality should be hidden behind a password/access code that we hand out.
  • Different rep groups selling to professionals need to have their own code that can be tracked
  • We want to see total conversion for each code used

My thoughts lead to why not use the existing conversions plugin I built?  I’ll just hide all of WooCommerce behind a password wall.  Any password the admin creates can be used to access it, I just drop a cookie.

I also drop a cookie for the Quick Tracking Conversions plugin and voila, our shoppers have access and we can see what password/access code they are using to make their purchase.  The new extension can be found here:

https://github.com/ChrisFlannagan/qtc-passwords