Chuck Grimmett

Development

Taxonomies

  • Advent of Code, Day 1: Picking a Project

    I’ve wanted to do Advent of Code for a few years, but I just can’t get excited about random puzzles. Not knocking all the folks involved in it–more power to you! It just isn’t for me. So I haven’t participated.

    Last week while flipping through a seed catalog to figure out what I’m going to plan in my garden next year, I had an idea: I want to build a plant starting/harvesting calendar for my garden. Building that will be my own Advent of Code project this year.

    Today was Day 1, planning day.

    Name

    Plant Gantt. Amanda came up with it and it is perfect. A gantt chart for plants.

    Goals

    1. Build an interactive planting/harvesting calendar for vegetables.
    2. Deploy my own Ember app with a user login system on something like EmberFire
    3. Beef up on my D3 and Ember skills.
    4. Use Tailwind for the first time
    5. Make progress every day.

    Features

    • Ability to add a plant name, seed start date, days to maturity, and pick a label color for it.
    • Visualize the plant’s growing period on a 52 week calendar
    • See the current day marked across the full calendar
    • Ability to hover over a plant and see how long it has been growing and how long left until harvest
    • Ability to create an account and save your calendar
    • Ability to print the calendar you created
    • Ability to create multiple calendars with unique names

    I may not get this done in 25 days, but I intend to make progress every day. It will be tough with the month ahead: Two out of state trips, moving into our new house, and holiday parties. I’ll carve out time every day to get some work done, though.

    Today’s progress

    1. Picked a name and got a domain
    2. Planned out the features and my goals for the project
    3. Set up the git repo and basic Ember app
    4. Install add-ons: ember-d3, ember-cli-tailwind

    Tomorrow’s goal

    • Figure out the basics of the D3 gantt-style chart
  • How to download inline SVGs

    I find myself regularly scouring business websites for logos to use. More and more of them use build pipelines that take all SVGs and embed them inline, making it impossible to just right click and download the image.

    Here is my short workflow for downloading inline SVGs:

    1. Open up your inspector and copy the whole SVG element.
    2. Open your favorite text editor (mine is VSCode) and paste the whole SVG element you just copied into a new file and save it as companyname.svg
    3. Open your new companyname.svg in Sketch.app and change the colors if needed. Sometimes the colors are applied via CSS, which won’t come in with the SVG element.
    4. Export the logo as your filetype of choice. Mind the size because inline SVG elements are often small. I usually export PNGs at @2x.

    Note: I still use steps 3 and 4 even if my end goal is SVG. First, I want to make sure the colors are correct. Second, Sketch adds some important attributes to SVGs like Viewbox that are helpful if you are using the file on the web.

    Here is a video I made walking through the process:

  • Building a reading list with Jekyll data files

    I transitioned by previous book notes section to a new reading list section. Why?

    1. I read a lot of fiction and don’t tend to take notes on it
    2. I wanted to keep a list of books I’ve finished.
    3. The book notes was not a great medium for doing #2. Writing the full set of notes was a pretty big barrier most of the time and I tended to go a few months at a time without updating the page, creating a large backlog.
    4. I came across Frank Chimero’s reading pageArchived Link and loved it. I also noticed that James Somers takes a similar approach with just listing the books out.

    So, I decided to implement Frank Chimero’s design with my own reading list.

    Instead of just hardcoding them in a page and repeating tons of HTML for the rest of my life, I decided to put the reading list in a Jekyll data file (I chose yaml) that I could easily add to and make a simple template to output.

    First, I started with my previous book notes section. Since they were stored in a Jekyll Collection, I was able to write a quick Liquid for loop to generate most of my list for me. But I didn’t want to: include a full star rating, just a recommended star. So I chose to star books that I rated 5/5:

    {% assign reviews = site.book_reviews | sort: "date" | reverse %} {% for review in reviews %}  - title: "{{ review.title }}"   author: {{ review.author }}   link: {{ review.book-link }}   star: {% if review.stars == 5 %}yes{% else %}no{% endif %}  {% endfor %}

    The result looked like this:

    - title: "Stories of Your Life and Others"   author: Ted Chiang   link: http://amzn.to/2Ghql7a   star: yes  - title: "A Burglar's Guide to the City"   author: Geoff Manaugh   link: http://amzn.to/2rElHgb  - title: "The Story of Sushi: An Unlikely Saga of Raw Fish and Rice"   author: Trevor Corson   link: http://amzn.to/2DAvzct  - title: "The Island at the Center of the World: The Epic Story of Dutch Manhattan and the Forgotten Colony That Shaped America"   author: Russell Shorto   link: http://amzn.to/2yqLmaE   star: yes 

    Awesome! That spit me out a list of everything I’ve written book notes for. Since it is sorted by date in reverse chronological order, it was quick for me to manually break it up by year:

     - year: "2019"     books:       - title: The Summer Book         author: Tove Jansson         link: https://amzn.to/2ZMtUuC         star: yes        - title: "The Last Pirate of New York"         author: Rich Cohen         link: https://amzn.to/34h0Oa3         star: yes        - title: "Fall; or, Dodge in Hell"         author: Neal Stephenson         link: https://www.amazon.com/Fall-Dodge-Hell-Neal-Stephenson/dp/006245871X         star: yes  - year: "2018"     books:       - title: "The World is a Narrow Bridge"         author: Aaron Thier         link: https://amzn.to/2PK3OZc        - title: "Fashion Climbing"         author: Bill Cunningham         link: https://amzn.to/2PJqkgz        - title: "Cape Cod"         author: Henry David Thoreau         link: https://amzn.to/2ZIISBV        - title: "The Outermost House"         author: Henry Beston         link: https://amzn.to/2MOf3hb         star: yes 

    Excellent. Two more steps:

    1. I want a “last updated” key so I only have to update one file. That means I need to nest the years under a parent key in order to access them.
    2. I need to manually add the books that weren’t in my notes but I know I read. This took me a few hours to get the books, authors, and links.

    Once I added the “last updated” key, the yaml structure looked like this:

    lastupdate: September 3, 2019 list:   - year: "2019"     books:       - title: The Summer Book         author: Tove Jansson         link: https://amzn.to/2ZMtUuC         star: yes        - title: "The Last Pirate of New York"         author: Rich Cohen         link: https://amzn.to/34h0Oa3         star: yes        - title: "Fall; or, Dodge in Hell"         author: Neal Stephenson         link: https://www.amazon.com/Fall-Dodge-Hell-Neal-Stephenson/dp/006245871X         star: yes        - title: The Boatbuilder         author: Daniel Gumbiner         link: https://amzn.to/2Lgvh0l    - year: "2018"       books:         - title: "The World is a Narrow Bridge"           author: Aaron Thier           link: https://amzn.to/2PK3OZc          - title: "Fashion Climbing"           author: Bill Cunningham           link: https://amzn.to/2PJqkgz          - title: "Cape Cod"           author: Henry David Thoreau           link: https://amzn.to/2ZIISBV          - title: "The Outermost House"           author: Henry Beston           link: https://amzn.to/2MOf3hb           star: yes 

    Here’s how I loop through that data to create my reading page:

    {% for entry in site.data.reading.list %}    

    {{entry.year}}

    {{entry.books | size}} books
    {% endfor %}

    Note that {{entry.books | size}} line: This is what outputs the number of books I’ve read in a particular year by spitting out the size of the books array. This is one of the big benefits of using a data file instead of hardcoded HTML or markdown. Just add a new book and everything else updates itself. Plus, I can use the data file for other things later if I so choose.

    Here is the result:

     reading list

    You can check it out over at the reading list page, or you can see the code over at my Jekyll Tools Github repository.

    If you liked my book notes, don’t worry. They aren’t going anywhere. I’m keeping the pages up for posterity, but I’m not updating them any more.

  • Adding Homebrew MySQL Service to your PATH

    If you install mysql via Homebrew ($ brew install mysql) and start it via Homebrew services ($ brew services start mysql), chances are that you’ll see an error when trying run mysql -u root on the command line.

    If that error is command not found: mysql, the issue is likely that you need to add the Homebrew mysql directory to your PATH.

    On my machine, Homebrew installed mysql here:

    /usr/local/Cellar/mysql@5.7/5.7.25/ 

    To add this to your PATH, add this to your .bash_profile (or .zhsrc if you use ZSH):

    export PATH=/usr/local/Cellar/mysql@5.7/5.7.25/bin:$PATH 

    Then, reload your shell and type mysql -u root to confirm all is working.

    You can quit the mysql CLI via mysql> q

  • Getting around foreign key constraints when restoring a Craft CMS database

    Are you getting foreign key constraint errors when trying to restore Craft CMS database backups? Here is how to solve it.

    Every time I download a backup of a Craft 3 database and try to restore it to my local development environment, I get this error: Cannot add foreign key constraint

    This happens because the SQL dump has the data in a different order than it should be loaded in according to the foreign key constraints.

    The solution is to use a MySQL session variable to turn off foreign key constraints and be able to load your data in the order it is currently in.

    How?

    WARNING: Do NOT even think of doing this in your production environment. Only development. You’ve been warned.

    Open your .sql dump in your favorite text editor and put this line at the top:

    SET FOREIGN_KEY_CHECKS = 0;

    Save it, then retry your import. Works for me every time.

    I wrote this post so that I don’t have to search how to do it in six months when I need to do it again.

    p.s. if you want to do something similar in postgres instead of mysql, search for SET CONSTRAINTS ALL DEFERRED.

  • How to Upgrade from PHP 5.6 to 7.2 for WordPress

    How to Upgrade from PHP 5.6 to 7.2 for WordPress

    Last week I updated three large WordPress sites for Praxis from PHP 5.6 to 7.2. Here is the process I used on all three to make it a smooth transition.

    Note: I do contract work and can help you figure this upgrade out. Reach out if you are interested in getting a quote.

    1. Figure out the scope of the problem.

    First you need to know how much time you should plan to spend doing this work. A quick way to find the scope of the problem is to run the PHP Compatibility Checker plugin. It checks your themes and plugins, spitting out errors, warnings, and filenames/line numbers of the offending code so you know where to start.

    • Small theme upgrades?
    • Plugin updates?
    • Massive refactoring of custom code?

    Even if you get a 100% clean pass with the compatibility checker, I suggest going through the rest of my list. The compatibility checker isn’t perfect. You don’t want to roll those downtime dice. Fool me one time, and all that.

    2. Test the upgrade locally.

    Copy down your current theme and database into your local development environment. This is important. Don’t use the version you have from work you did a few months ago. Stuff changes on the server all the time. Pull down a copy to be safe. Configure your local environment to use PHP 7.2. If you are unsure whether or not you are on 7.2 locally, you can always use a WordPress plugin like Debug Info to check. Also make sure to turn on error reporting in your php.ini.

    Don’t have a local development environment yet? I like Valet.

    While you are at it, I suggest upgrading your WordPress core to the latest version (5.1.1 as of this writing) and updating all of your plugins. Rip that bandaid off. On the plus side, it will probably make the PHP upgrade process easier, too.

    3. Find, diagnose, and solve any issues.

    This is either the easiest or hardest step. If your site looks fine and everything functions as it should, great! You won the lottery.

    It is probably worth double checking that you actually are on PHP 7.2 with the debug plugin mentioned above. Also worth clicking all around your site and checking everything. Sometimes most of the site will load, but you’ll get weird inline error messages like this:

    Warning: Use of undefined constant Y - assumed ‘Y’ (this will throw an Error in a future version of PHP) in /nas/content/staging/creativecourse/wp-content/themes/business-pro-theme/page-archive.php on line 70 

    If you navigate to the site locally and all you see is a sea of errors like I did on one site, you have some work cut out for you. Here are some tips:

    • If the errors include wp-includes or wp-admin in the file paths, you need to update your WordPress core.
    • If the errors include wp-content/themes/ in the file path, and you don’t have any custom work done on the site, the quickest fix is to upgrade your theme or find a new one.
    • If the errors include wp-content/plugins/somepluginname/ in the file path, find that plugin and disable it or update it and try again. You should still be able to get to your /wp-admin/ dashboard even with a broken site because the most recent core works with PHP 7.2.
    • If your site includes a bunch of custom code and the errors are happening with the custom code, you have more work to do. If you are comfortable debugging and fixing it, great! If not, you might need to call the person or company who wrote it. Or decide if you can do without it. Hopefully you followed conventions and put it in a child theme.

    Keep track of the changes you make. I keep a running list in my favorite notes app. Theme updates, core updates, plugin updates, and code changes. Write it all down. Better yet, version control it with git and commit along the way.

    If you have any premium plugins that require activation keys, make sure that you contact the developer to get two extra development keys for local testing and production. Most will provide those to you at no extra cost. Some platforms give you 5 keys per purchase anyway just for this reason. I decided to roll the dice and not get keys for one plugin, and ended up crashing my production site with the upgrade because I didn’t test that plugin. Don’t be like me.

    All three of my sites needed some work done, even the newest of the three. One didn’t load at all until I made some theme updates. One plugin crashed a site and had no updates available, so I had to do without. Some custom code I had written needed updates, too. It took me a few afternoons to sort it all out.

    4. Deploy to a staging environment on PHP 7.2 first.

    Once you have everything sorted out locally and you’ve triple tested everything, go ahead and push your work up to a staging environment. Good hosts like WPengine make having a production and staging environment easy. You can control the PHP versions independently. I use WPengine’s git deployment to move my local updates to the staging server. SFTP works, too. If you need database changes, you’ll also need to do a database migration. Core and plugin updates will need a database migration (Don’t forget to change the site URL or you won’t be able to log in!) If you need to do a database migration, use the instructions here

    My preferred workflow is to copy the full production site (code + database) to staging, push my code changes, then do the core and plugin upgrades on the server (they often involve database changes), which is when my change list above comes in handy. I don’t like doing database migrations unless I absolutely have to, because with lots of users logging in to the site, data is bound to get out of sync with my local version in a matter of hours. Getting back in sync is tricky, so I choose to avoid the problem altogether by only moving code, keeping my change file, and replaying the steps on the staging server.

    If you don’t have a staging environment and can’t get one with your host, or you can’t upgrade the PHP version yourself on your host, then you need a different plan. You’ll need to set up another site on another host that uses PHP 7.2, then put the updated copy of your site there. If you do this,proceed to the alternate #5 below.

    Don’t assume everything works. Test it! Use different user account levels (admin, editor, author, contributor, and subscriber). Try every critical function on your site.

    Only move on to the next step when you are certain everything works like it should.

    5. Deploy to production.

    Before you do anything else here, make a back up of your site and your database. Good hosts like WPengine make this easy. If you are doing this manually, verify the backups work locally. You can to be able to roll back if there is an issue.

    I planned a maintenance window with my users a few days ahead of time. If you have users who rely on the site, you should, too.

    Update your production environment to PHP 7.2, then copy the staging server to the production server. If you are confident that there were no users updating content in between the staging copy above and now, you can copy database and all. If there are changes you don’t want to lose on the production database, you’ll need to use my method and only copy over the theme code, then do core and theme updates on the production site. This is when planned downtime comes in handy.

    Alternate deploy (no staging)

    If you set up a separate site on 7.2 (not a staging environment of a production site) and it works, then you are ready to cut over to the new version. Configure that new site to use your domain (URL field on the setting page), then point your domain’s DNS records at the new server. If you need to do a database migration, use the instructions here.

    6. Verify everything works

    Don’t assume everything works. Test it! Use different user account levels (admin, editor, author, contributor, and subscriber). Try every critical function on your site. Use the Debug Info plugin to verify that the PHP change took.

    If there are any issues, you might need to roll back to an earlier restore point and PHP version (or point your domain back to your other server), or do some real-time debugging. If your production and staging servers mirror each other in every way except PHP version, you shouldn’t run into anything unexpected. If you do, figure out where the difference is and go back to #3 above.

  • Moving from Homestead to Valet for WordPress Development

    I used to use Homestead for local WordPress and Craft development. It was nice because everything worked out of the box. Well, theoretically. In reality, it worked about 80% of the time, but 20% of the time I’d get cryptic errors from Vagrant like:

    • Some box with the same name exists. We won’t tell you where, but trust us, it exists and that can’t happen.
    • The SSH command responded with a non-zero exit status. Vagrant assumes that this means the command failed. The output for this command should be in the log above. Please read the output to determine what went wrong.
    • Error! You have to destroy this box and rebuild it. Hope you backed up those local databases, because they are gone forever!

    It was always a rabbit hole of headaches that could take half a day to resolve. Most resolution happened in the form of me destroying a box and rebuilding it, losing my databases. So much fun.

    Today I got the SSH error again and had enough. I went looking for a better solution and found Valet. Their pitch:

    Valet is a Laravel development environment for Mac minimalists. No Vagrant, no /etc/hosts file. You can even share your sites publicly using local tunnels.

    Sounds great. It won’t eat my battery, RAM, CPU, or take gigs of disk space for vitual machines. Sign up the heck up.

    It was super easy to set up with tools I already use: Homebrew and Composer. Instructions here.

    The only tricky part was making composer directory available in my Mac’s PATH, since I’ve only ever used it inside individual projects. Turns out with zsh you have to give the explicit path, you can’t just use ~/, so I added this to my .zshrc: export PATH=/Users/cagrimmett/.composer/vendor/bin:$PATH

    Once I loaded the profile with source ~/.zshrc, I was good to go. I linked my main projects folder so Valet knows where to look for projects, changed my wp-config.php files to point at my local mysql database instead of Homestead’s, then navigated to project-folder-name.test and was good to go!

    Valet runs at startup, so I don’t have to run cd ~/Homestead && vagrant up anymore, just brew services start mysql@5.7 if I need a database running (which you usually do for WordPress development.)

    I like that Valet makes it so easy to use different PHP versions. For example, to use 7.2, you go to your command line and type: valet use php@7.2

    I’m looking forward to never using Vagrant or VirtualBox again. Peace out

  • Automated Accountability Check-ins

    Automated Accountability Check-ins

    The Need

    During the Praxis bootcamp, participants are expected to make every single day a non-zero day. Most participants ask us to hold them accountable, so they email one of our staff each day and that person emails them the next day if they miss a check-in. This takes an enormous number of emails, staff overhead to keep track of, and is difficult to search. Isaac asked me, “What can we do to automate this?”

    It needs this functionality:

    1. The ability to submit what you’ve worked on that day.
    2. The ability to see what you’ve submitted.
    3. The ability for staff to see what you’ve submitted.
    4. The ability to send an email to people who didn’t submit a check-in the previous day.
    5. The ability for logging who missed a check-in.

    The Restrictions

    There are existing systems that do this sort of thing, so why make our own? During the bootcamp, our customers use what we call The Portal, which is a curriculum platform I built on top of WordPress with the help of Restrict Content Pro and wpcomplete. I didn’t want to add another destination into the mix. I wanted a reason for customers to go to the Portal every day and keep their work moving forward. Plus, they already have logins there. No need to add yet another login for them to keep track of.

    The Solution Sketch

    1. USP Pro for front-end post submission
    2. Custom page template to display the content box but hide the tedious stuff: User ID, today’s date, user email
    3. New WordPress user meta field for keeping track of accountability opt-ins
    4. Custom script to check if opt-ins have posted within the last 28 hours and fire off a webhook to Zapier to send the email and log missed check-ins to a spreadsheet
    5. Zapier time trigger with a GET hook to run the script at a specific time to kick off the accountability check
    6. Custom template to display all opted-in participants and their check-ins to make it easy for staff to see everything in one place
    7. Hide the check-ins from search results

    The Solution Details

    Front-end post submission and showing posts

    USP Pro handles all sorts of complexity when it comes to submitting posts from the front-end of a WordPress site: The form, the custom post type, assigning the current logged-in user to be the author, and displaying success and error messages. They also have hooks and filters to make using the posts in templates easier.

    I used a custom template to hide some of the things I’d need to make the whole process work: User ID to assign as the post author, name and today’s date for the title of the post.

    After the form, we also want to show all the posts someone has already submitted. I do that with a WP_Query_  Note: I added a Delete button here in case some makes an accidental post. If you want someone to be able to delete their check-in post, they need to have the role Author.

    Here is the code I used for the template and comments about what it does:

    // Check if user is logged in. Display the check-in form if so, login form if not. if ( is_user_logged_in() ) { //Get the logged in user, today's date, and the PHP session ID 	$current_user = wp_get_current_user(); 	$today = date("F j, Y"); 	$ses_id = session_id(); ?>    class="usp-pro-form">  	 	 id="usp-pro" class="usp-pro usp-form-4102"> 	 id="usp-form-4102" class="usp-form" method="post" enctype="multipart/form-data" action="" data-parsley-validate="" data-persist="garlic">  		 class="usp-fieldset usp-fieldset-default"> 			 for="usp-content" class="usp-label usp-label-content">

    What did you do to make today a non-zero day?

    name="usp-content" id="usp-content" rows="5" cols="30" maxlength="999999" data-required="true" required="required" placeholder="Today I..." class="usp-input usp-textarea usp-input-content"> type="hidden" name="usp-content-required" value="1"> class="usp-hidden"> // Get first and last name, today's date, set that as the title. echo '. $current_user->user_firstname . ' ' . $current_user->user_lastname . ' ' . $today . '" type="hidden" />'; // Get user ID for author echo '. $current_user->ID . '">'; // Get PHP session ID. Plugin thing. echo '. $ses_id . '">'; ?> type="text" name="usp-verify" id="verify" value="" style="display:none;" class="exclude"> type="hidden" name="usp-form-id" value="4102">
    echo do_shortcode('[usp_form id="submit"]'); ?>
    class="submitted-checkins">

    Your submitted check-ins:

    // Show posts from this user ID with the type usp_post $post_query = new WP_Query( array( 'post_type' => 'usp_post', 'author' => $current_user->ID, 'orderby' => 'date', 'order' => 'DESC', ) ); if ( $post_query->have_posts() ) : while( $post_query->have_posts() ) : $post_query->the_post(); ?> post_class(); ?>>

    the_time('F j, Y \a\t g:i a') ?>

    the_content(); ?> href=" echo get_delete_post_link(); ?>" style="font-size: .8em;">Delete this check-in
    endwhile; else: echo "

    You have no check-in posts. Submit one above!

    "
    ; endif; ?>
} else { ?> style="padding:50px;"> echo do_shortcode('[login_form]'); ?>
} ?>

The page (with a little bit of CSS added, which I’ll leave as an exercise for the reader) looks like this: Automated Accountability Check-in Home Page

Adding custom user meta field for accountability opt-in

This goes in functions.php:

add_action( 'show_user_profile', 'accountability_opt_in' ); add_action( 'edit_user_profile', 'accountability_opt_in' );  function accountability_opt_in( $user ) { ?>  	

Daily Accountability

class="form-table"> for="checkin">Opt in to daily check-in accountability? type="checkbox" name="checkin" id="checkin" if (get_the_author_meta( 'checkin', $user->ID) == 'True' ) { ?>checked="checked" }?> value="True" /> /> class="description">Yes, opt me in. } add_action( 'personal_options_update', 'save_accountability_opt_in' ); add_action( 'edit_user_profile_update', 'save_accountability_opt_in' ); function save_accountability_opt_in( $user_id ) { if ( !current_user_can( 'edit_user', $user_id ) ) return false; update_usermeta( $user_id, 'checkin', $_POST['checkin'] ); }

So, at the bottom of the user profile, it now shows this: Automated Accountability Check-in User Meta Field

Checking to see if opted in user has submitted a post in the last 28 hours

Outline:

  1. I trigger this by hitting the URL once a night. So no one else can trigger it, hit it with a long random key as a query string, which I first get and check.
  2. Load WordPress so I can use pre-built functions.
  3. Get list of opted-in users.
  4. Check to see if they have posts. If so, get the most recent one. If not, send a webhook to Zapier.
  5. If they have posts, check the date of the most recent one. If it is within the last 28 hours, do nothing. If not, send a webhook to Zapier. 28 hours gives a little wiggle room for early/late posts.

I like to leave the echos on for debugging if something goes wrong. Like, for example, if you use the_date instead of get_the_date and occasionally get NULL instead of a date and can’t figure out why. (Hint: the_date only fires once in a loop. Thanks for the help debugging, Eric Davis!)

Also, I know I’m using two different types for formatting for if statements. It helps me keep them separate.

 $key = $_GET['key'];  if ($key == 'RANDOM_KEY' ) {  	require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');  	function get_user_by_meta_data( $meta_key, $meta_value ) {  		// Query for users based on the meta data 		$user_query = new WP_User_Query( 			array( 				'meta_key'	  =>	$meta_key, 				'meta_value'	=>	$meta_value 			) 		);  		// Get the results from the query, returning the users 		$users = $user_query->get_results();  		return $users; 	}  	$opted_in_users = get_user_by_meta_data( 'checkin', 'True');  	foreach ($opted_in_users as $user) { 		echo $user->ID . ' ' . $user->user_email . '
'
; $post_query = new WP_Query( array( 'post_type' => 'usp_post', 'author' => $user->ID, 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'DESC', 'showposts' => '1', ) ); // The Loop if ( $post_query->have_posts() ) : while ( $post_query->have_posts() ) : $post_query->the_post(); $date = get_the_date('U'); echo 'last post date: ' . $date . '
'
; //echo 'now: ' . time() . '
';
if( $date > (time() - 100800)) { echo 'Within 28 hours

'
; continue; } else { echo 'Not within 28 hours

'
; // Initialize curl $curl = curl_init(); $data = array( 'user_id' => $user->ID, 'email' => $user->user_email, 'first_name' => $user->first_name, 'last_name' => $user->last_name, 'last_post' => $date, ); $jsonEncodedData = json_encode($data); $opts = array( CURLOPT_URL => 'https://hooks.zapier.com/hooks/catch/1503890/aqztv5/', CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $jsonEncodedData, CURLOPT_HTTPHEADER => array('Content-Type: application/json','Content-Length: ' . strlen($jsonEncodedData)) ); // Set curl options curl_setopt_array($curl, $opts); // Get the results $result = curl_exec($curl); // Close resource curl_close($curl); echo $result; } endwhile; else : echo "No posts

"
; // Initialize curl $curl = curl_init(); $data = array( 'user_id' => $user->ID, 'email' => $user->user_email, 'first_name' => $user->first_name, 'last_name' => $user->last_name, ); $jsonEncodedData = json_encode($data); $opts = array( CURLOPT_URL => 'https://hooks.zapier.com/hooks/catch/1503890/aqztv5/', CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $jsonEncodedData, CURLOPT_HTTPHEADER => array('Content-Type: application/json','Content-Length: ' . strlen($jsonEncodedData)) ); // Set curl options curl_setopt_array($curl, $opts); // Get the results $result = curl_exec($curl); // Close resource curl_close($curl); echo $result; endif; } } else { exit("You are not authorized. Go away."); } ?>

Template for viewing posts by user

Viewing posts in the wp-admin area is less than ideal. They are grouped by date instead of author and the full contents doesn’t show unless you click. No want to view updates at a glance. So I made a template for that.

// First, check if user is an admin. if ( !is_user_logged_in() || !current_user_can('administrator') ) { 	   wp_redirect( site_url() );  exit; } else { // User IDs are passed via query string. If no string, show all names 	$user = $_GET['id']; if ( $user == null ) {?> 	

Participants who have submitted check-ins:

$args1 = array( //'role' => 'author', 'orderby' => 'first_name', 'order' => 'ASC' ); $authors = get_users($args1); foreach ($authors as $user) { $user_post_count = count_user_posts( $user->ID , 'usp_post' ); if ( $user_post_count > 0) { echo '. $user->id . '">' . $user->first_name . ' ' . $user->last_name . '
'
; } } } else { $user = get_user_by('id', $user); $post_query = new WP_Query( array( 'post_type' => 'usp_post', 'author' => $user->ID, 'orderby' => 'date', 'order' => 'DESC', ) ); ?> />

href="/check-ins/">← Back to all participants with check-ins

echo $user->first_name . ' ' . $user->last_name .'\'s check-in posts';?>

if ( $post_query->have_posts() ) : while( $post_query->have_posts() ) : $post_query->the_post(); ?> post_class(); ?>>

the_time('F j, Y \a\t g:i a') ?>

the_content(); ?>
endwhile; else: echo "

You have no check-in posts. Submit one above!

"
; endif; } }

Here is what the template outputs:

check-in post user list

user posts

The best way to do this is to hook in to when the post type is initiated and toggle the ‘exclude_from_search option so ‘true’. I added this to functions.php:

add_action( 'init', 'usp_post_hide_search', 99 );  function usp_post_hide_search() { 	global $wp_post_types;  	if ( post_type_exists( 'usp_post' ) ) {  		// exclude from search results 		$wp_post_types['usp_post']->exclude_from_search = true; 	} } 

Using Zapier

I opted to use Zapier for two things:

  1. Triggering the nightly post checking script via GET. wp_cron isn’t super reliable if you need something to run at a given time, and since I’m hosting on WPengine, I don’t have access to the server cron. We already use Zapier for a ton of stuff, so I fire off a GET to my script with the query string random key.
  2. Sending the email and logging emails sent. I could have done this all in the script, but I wanted staff to be able to easily change the email and possibly add more post-email items like sending a message to Slack and Salesforce, or sending a text message to the user.

Going Forward

Here are a few ways I want to improve this when I have time:

  1. Extend the template that staff uses to see check-in posts to include filter criteria.
  2. Let users opt-in and opt-out of automated accountability instead of admins opting them in or out.
  3. I might want to expire or hide posts
  4. USP by default doesn’t preserve line breaks. I’ll need to update that.
  • Rebuilding cagrimmett.com and Moving Old WordPress Posts to Jekyll

    Rebuilding cagrimmett.com and Moving Old WordPress Posts to Jekyll

    Earlier this week I did a major revamp of cagrimmett.com. It started with redesigning my page templates to include a sidebar, then it morphed into making a long-standing goal of mine reality: Reviving the posts from my old 2008-2012 WordPress blog and getting them into Jekyll.

    The Redesign

    The redesign started as a seed in my mind when I visited http://datavisualizi.ngArchived Link a few months ago. I loved the look of the sidebar with the social links. What I didn’t love about it was the way the menu works and how the sidebar is sticky. I noticed the site is also built on Jekyll, so I briefly considered installing the theme, but I decided against it after about 30 seconds. I wrote most of my current theme myself and don’t want to mess up my TIL and Book Notes templates. So I took an afternoon and rewrote some of my templates to include a sidebar.

    The trickiest part was figuring out what I wanted to do with the sidebar on smaller screen sizes. I decided to push it up to the top on pages, show the social buttons on the Home and About pages, and then hide it altogether on posts.

    The other main issue was what to do with featured images. My templates were built to include featured images on posts before, but this time I decided to make them optional. The home page and archive pages don’t display featured images, but the category pages do.

    Migrating my Microblog to Jekyll

    Last year I started a Microblog, built a custom theme for it, and posted there 116 times over a few months.

    I found it confusing to have multiple places to store content, so I decided to consolidate. I’m keeping cooklikechuck.com separate, but I’m killed cagrimmett.com and moved all the posts here. This was originally on WordPress, so it a small test case for whether or not it would be possible to resurrect my old 2008-2012 blog and migrate the posts to Jekyll.

    There is an official jekyll-import gem that supports WordPress, so I figured that this was going to be a piece of cake. That is, until I tried to install the gem. An hour later and 5 dependencies deep down the debugging rabbit hole, I finally gave up. Cryptic error messages somewhere around the mysql2 dependency finally made me throw in the towel and go to bed.

    I woke up the next morning with a renewed sense of confidence and started searching. I came across this WordPress to Jekyll exporter, which worked phenomenally well. It dumped all of my posts out as .md files with the WordPress metadata translated into YAML front matter.

    I was a little worried about what to do with all of the image links, but then I realized that all uploaded images in WordPress are stored at /wp-content/uploads/year/month/filename.jpg. If I add that /wp-content/uploads/ directory to Jekyll wholesale and replace all instances of cagrimmett.com with www.cagrimmett.com, all images in posts will work! So I pulled the directory down off my server, dusted off my grep skills, and everything worked as intended. Success.

    The only other hiccup was that about half of my posts on the microblog didn’t have titles. That is part of the whole microblog philosophy. Those posts showed up in my main feed with just ID numbers, which looks strange. I solved that by adding hidden: true to the posts to hide them from the Jekyll paginator. Win number 2 for the old grep skills.

    Resurrecting CAGblog

    After my success with copying over my microblog posts, I decided to kick the difficulty up a notch and see if I could move over 500 posts from my old 2008-2012 site, which I affectionately called CAGblog. I was eager to get this stuff back online because 2008 is when I first started blogging, and I wanted my internet cred back. I know some of my stuff from when I was 18 is pretty cringeworthy, but having my old stuff up for posterity really matters to me.

    Here is one of the few screenshots I have of it, from 2008:

    CAGblog

    Before I shut the blog down in 2013 and put up a landing page in its place, I made a backup and promptly forgot where I stored it. After hours of searching old hard drives, I finally found it on dropbox.com. It hadn’t synced to my local machine because I had selective sync turned on. I almost panicked earlier because I thought I had lost all my old stuff. Thank goodness for Dropbox!

    The first step in the revival was to restore my old database to a working WordPress site so that I could install the Jekyll exporter plugin. I only really needed the posts, not a complete working site, so I ignored all my old post templates and stuff. The database was from an early version 3 of WordPress, so I was concerned that it wouldn’t work on my Homestead dev environment and I’d have to go hunt down an old WordPress install somewhere. Thankfully WordPress has a bunch of update routines in place to handle just this kind of thing, so after going through a few “You need to update this database” prompts, I was able to log in to the wp-admin area and access all my old posts.

    Just like on cagrimmett.com, the WordPress to Jekyll exporter worked exactly as intended. Now the fun began: I had a ton of old categories and tags I didn’t want to use, old images I needed to find and get linked up, and old links that needed to be rewritten.

    Categories and Tags

    For categories and tags, I simply edited the yaml metadata on the old posts and changed the keys to oldcategories and oldtags so that Jekyll wouldn’t parse them as normal. Grep win number 3.

    For old images, I used the same method as on my microblog: I moved the wp-content/uploads/ folder to the root of my Jekyll site. That took care of about 50% of the broken images. The rest were scattered around other folders, so I searched for broken images, looked at where they were, and moved over every folder I could find. There are a few casualties, namely images that I didn’t host myself, but the vast majority are back up and running. I was a n00b 10 years ago and just threw stuff in my main directory, so now I have a bunch of old stuff cluttering up my previously pristine main Jekyll folder. Perhaps one day I will move all that to more logical folder structure and write redirects, but for now it is all staying where it is.

    The links aren’t easy to preserve on a static site because I used the default post ID permalinks on my WordPress site. Those are the ones that look like website.com/?p=2347. I used the permalink key in Jekyll to set the permalink to /blog/[oldid].html. (Another win for grep. Man, regex is useful.) Then I followed this post to do some apache magic, fetch the ID from its query string, and redirect it to its new home. Now all of my old post links redirect to their new home on my Jekyll site! I clicked a few old ones from Facebook just to make sure.

    When I moved to Cloudflare, my site search broke. With all of this old content back on my site, I knew I needed to get search working so the posts are findable, so I took a look at it again. The issue was that I had been submitting the form action to the same page. The query string didn’t get preserved with all the redirects/rewrites I’m doing/Cloudfront does, so I edited the submit function to just kick off the JS search function with the query directly instead of submitting/refreshing the page. Go run some searches and dig through my archives!

  • Simple Microblog WordPress Theme

    Simple Microblog WordPress Theme

    When I learned about the Micro.blog project by Manton Reece, I decided that I wanted to host my own microblog, so I made a minimalist microblogging WordPress theme for that purpose.

    I put it out on Github for others to use: https://github.com/cagrimmett/simplemicroblog-wp

    Screenshot

    Particulars

    Credits

  • ,

    Want to learn to program? Actually building things is the best way to learn. Here is a great list of projects that you can complete in popular languages: https://github.com/tuvttran/project-based-learning

  • HTML and CSS Basics for WordPress

    HTML and CSS Basics for WordPress

    Here are resources for WordPress users who want to use HTML and CSS to alter the structure, look, and feel of their themes, posts, and pages.

    What HTML and CSS do

    HTML is for structure, CSS is for presentation, and Javascript is for behavioral interaction

    HTML is primarily for structure. HTML is the base level of most what you see right now in your internet browser. In order for any CSS or Javascript to work on content, that content must be first wrapped in an HTML tag.

    CSS is primarily for presentation. CSS is essentially a shorthand way of giving instructions to HTML tags on how they should look and where on they page they should show up. CSS does include some behavioral interactions components like hover and on-click actions.

    Javascript is primarily for behavioral interaction, but its scope has grown significantly in the past few years. We won’t cover Javascript in this guide. It requires its own guide, which will come later.

    Resources

    My favorite resource for learning the basics of HTML and CSS from scratch is W3Schools. Their examples are clear and they have widgets where you can test out the syntax and poke around what already works to learn more.

    Here is the W3Schools HTML tutorial. I recommend completing the HTML HOME through HTML Symbols. This will cover 95% of the HTML you will encounter in WordPress.

    Here is the W3Schools CSS tutorial. I recommend completing CSS HOME through CSS Forms. This will cover the basics of the CSS that you will see in WordPress. Pay particular attention to the Box Model. Once you feel comfortable with the basics, feel free to move on to the CSS 3 section, which builds on the basics.

    After you’ve gotten your feet wet with W3Schools, test your knowledge by working your way through Codecademy’s HTML and CSS course.

    How to use these resources

    The best way to learn HTML and CSS is by actually writing it, refreshing the page, and seeing what happens. A good rule is to spend 3 hours applying for every 1 hour reading/taking notes.

    Get yourself an easy-to-use text editor like Atom, make a new file names hello.html, and then start writing. After you’ve written your first line, save the file and open it in your web browser to admire your handiwork.

    Then go back to Atom, make some changes, save, and then hit Refresh in your browser. Repeat.

    To find which style definitions and HTML tags apply to what you see on your favorite websites, learn how to use Chrome’s debugger to find them. After a little practice you’ll be able to quickly identify the underlying markup and apply your own overrides and fixes.

    Where you’ll use HTML and CSS in WordPress

    You’ll primarily use HTML in the content editor of Posts and Pages. When you are editing a post or a page, the editor has two options: Visual or Text. Visual comes up by default. If you switch over to the Text tab, you’ll see that your headers, lists, etc are marked up with HTML:

    HTML in the WordPress post editor

    CSS is usually defined and applied in the style.css file inside your WordPress theme folder. That said, if you are just starting out, I recommend you leave the style.css file alone and install the Jetpack plugin. It includes a module for adding custom CSS to your theme. There are two benefits for doing it this way:

    1. Beginners should stay away from theme files because you can easily crash your site if you don’t know what you are doing. Changes made in the Jetpack CSS module don’t change your theme, they just apply changes on top of it. These changes are easy to remove, so you don’t have to worry about crashing your site.
    2. These changes are stored in the database, so they’ll bypass cache. Most hosts aggressively cache theme files, so changes made directly to style.css might take some time to show up. Changes applied via Jetpack’s CSS module take effect as soon as they are saved. These changes are also usually applied last, so they take precedent over what is defined in your theme.

    The free version of the Jetpack plugin is all you need. Once it is installed, you can click “enable recommended options” and the CSS module should be included in that. If it isn’t, go to Jetpack > Settings > Appearance and toggle on Custom CSS.

    Once it is turned on, you can go to Appearance > Customize in your WordPress Admin sidebar. In the Customizer you’ll see an area for Additional CSS:

    Jetpack's Custom CSS module in the WordPress Customizer

    Questions

    If you have any questions, drop them below in the comments! Or, you can ask them on Stack Overflow and Quora like the rest of the web does 🙂

  • My WordPress Stack

    My WordPress Stack

    I’ve been building sites on top of WordPress and developing WordPress themes for the past five years. Here are the tools, hosts, themes, and plugins I use to build WordPress sites quickly and get the most out of them after they launch.

    Total Theme

    For the past two years, I’ve used the Total theme as the base I build off of. I’ve used more themes and theme frameworks than I can count, but Total is the one I keep coming back to.

    I chose the Total theme because it is highly configurable, it has solid documentation, includes a bunch of premium plugins, and it has tons of hooks and filters that you can use to add in custom programming. Pretty much everything in the theme is modular, so it can be quickly customized and reused without cascading effects.

    It is great to prototype with! All of the demos on the theme’s main site are built from the same theme with different configurations. You can install these demo options through the theme’s interface and build off of them. All of the customizations are able to be exported at JSON from the WordPress admin area, which makes it super easy to copy changes from staging to live.

    The custom post types Total has included for Staff, Portfolio, and Testimonials are super useful. I’ve expanded them to work for many things besides their traditional uses: job talent profiles, a collection of videos, a cocktail library, and book quotes.

    Here are some sites I’ve made using Total: Cook Like Chuck, AmandaKate.me, Nasty Design Co, MichaelMalice.com, RyanSosnow.skiArchived Link, The Commonwealth Partners, and Strong Roots NebraskaArchived Link.

    Plugins

    Here are the plugins that I use most often:

    Development

    Development Environment

    I primarily develop on virtual machines to keep my work from affecting my main machine. If something screws up, I can just delete the virtual machine and start over.

    I use Virtual Box to run the VMs, Vagrant to manage them, and Laravel Homestead as my base development environment. WordPress’s famous five minute install instructions work perfectly on Homestead.

    Staging and Production Environment

    For large sites that I work on, I always make sure we have two separate environments running at all times: Staging and Production. The production site is the live one that customers access. The staging site is a copy of the live site where all major changes are applied and tested first (function additions, template changes, plugin testing, etc). The production site should never have code on it that hasn’t been tested on the staging site first. Hosts like WPEngine include a staging area with every install by default. On shared hosting services like A Small Orange or Bluehost, you’ll need to set up a subdomain install to act as your staging environment.

    IDE

    Coda by Panic is my IDE of choice. I’ve been using it since it first launched and I stuck through the major 2.0 (and subsequently 2.5) release. It has highlighting, remote editing and publishing (via FTP/SFTP/SSH), previewing, SQL connectors, Terminal, regex search, and git support built in. Tons of third party add-ons available. I’ve written AppleScripts for it and know most commands by heart, so I’m unlikely to jump ship any time soon.

    Use a Child Theme

    Whenever you make any code changes to a WordPress theme, you should always do them from a child theme. Child themes allow you to change functions and templates and still preserve changes when the base theme is updated. Here is a child theme for Total.

    Hosting

    For Low Traffic

    For low traffic sites, a shared hosting account is all you need. This means your site is hosted from a server that hosts multiple sites at once.

    I use A Small Orange. I host Cook Like Chuck, AmandaKate.me, Nasty Design Co, and a theme staging area all on one of ASO’s Small accounts, which I pay $50 a year for. I’ve had up to 100 distinct users on Cook Like Chuck at the same time without an issue (thanks, Reddit!). I’d probably feel comfortable up to 200-300 distinct users on an ASO site at the same time without sweating as long as things are properly cached (see plugins below). Anything more than that and you’ll want to jump to something like WPEngine.

    Never opt for the “Tiny” version at A Small Orange. It is on cheaper, slower infrastructure, which is why the price is so low. It probably won’t even handle up to 100 concurrent users.

    ASO has great customer service. They are always available, even in the middle of the night!

    For High Traffic

    For high-traffic sites, I use WPEngine.

    Praxis had a huge traffic surge at the beginning of March when Isaac Morehouse went on Tucker CarlsonArchived Link. At the peak of the surge, we had around 7500 concurrent users (i.e. 7500 different people hitting the site at the exact same time) and we had no decrease in performance on WPEngine. They aggressively cache and have super fast servers. Cook Like Chuck (on an A Small Orange Small account) would have crashed under that load, even with caching plugins.

    WPEngine also has great customer support. They don’t let you tweak caching settings yourself, but a support agent will take care of it for you in minutes.

    For the Server Admin

    If you want to build out your own hosting environment, tweak caching settings, set up load balancers, etc, you can build out your own WordPress hosting environment on Amazon Web Services.

    At eResources, we had a great experience with hosting high traffic WordPress sites on Rackspace. Their support is top-notch.

    Backups

    Hosts like WPEngine automatically make backup points every night. On shared hosts, I have a recurring task scheduled to download a backup every Friday. I keep weekly backups for a month and monthly backups for a year. I store these on an external drive that is synced up to Backblaze.

    Domains

    I use Hover for buying and managing domain names and most DNS management. I use Cloudflare for DNS management on domains that need SSL because I love their Flexible SSL plan.


    What are your favorite WordPress tools? Let me know in the comments!

  • Adding Full Width Front Page Widgets to Genesis Themes

    Adding Full Width Front Page Widgets to Genesis Themes

    The Genesis Framework is super useful out of the box, but what if you want to color outside the lines?

    Two weeks ago my coworker Derek Magill asked me to take a look at this awesome full width box on GrooveHQ’s website that has a testimonial box on one side a video on the other. This goes edge-to-edge, which means that it is impossible to make in most Genesis themes out of the box.

    GrooveHQ Video Testimonial Box

    The Solution

    We want this to display on the front page, which means it needs to be a front page widget. I prefer hardcoding as little design details as possible in order to leave things as flexible and as reusable as they can be. This means that that architecture decision I chose is to not build the widget with dedicated area for the testimonial and video, but to just make the widget span the width of the full window instead of being constrained to the container. Everything else is going to be handled by HTML and Javascript inside the widget. That way we can reuse the full width widget for something else later if we no longer want the video.

    1. Register the widget area

    In WordPress, you register things inside functions.php. Make sure you do it in your child theme, not the main Genesis parent theme. Since Genesis typically comes pre-loaded with 5 widget areas, I opted to give this one the ID front-page-6. You can choose whatever you want, but make sure you carry the same ID all the way through:

    genesis_register_sidebar( array( 	'id'          => 'front-page-6', 	'name'        => __( 'Front Page 6', 'showcase' ), 	'description' => __( 'This is the 6th section on the front page. It is full-screen.', 'showcase' ), ) ); 

    2. Output the widget area on the front page

    In Genesis themes, the front page template is usually named front-page.php. This is where we’ll be putting this snippet. Find where the other front page widgets are output and add your new one in where you want it. Remember that in hard coded theme templates, the order matters. If you want it before all the other widget areas, you need to put the code that runs it first.

    A normal widget area that doesn’t go full width would look like this:

    genesis_widget_area( 'front-page-6', array( 	'before' => '
    . showcase_widget_area_class( 'front-page-6' ) . '">', 'after' => '
    '
    , ) );

    But if you want to remove the padding around the edges of the widgets that keep them vertically in-line with the rest of the content, you’ll need to remove the

    and one of the closing

    tags. Also remove the flexible-widgets class.

    genesis_widget_area( 'front-page-6', array( 	'before' => '
    . showcase_widget_area_class( 'front-page-6' ) . '">', 'after' => '
    '
    , ) );

    3. Add the classes you created to your theme’s style.css

    Here is what I opted to add:

    .front-page-6 {   background-color: #d64745;   color: #fff; }  .Aligner {   display: flex;   align-items: center;   min-height: 24em;   justify-content: center; }  .Aligner-item {   flex: 1; }  .Aligner-item--top {   align-self: flex-start; }  .Aligner-item--bottom {   align-self: flex-end; }  .Aligner-item--fixed {   flex: none;   max-width: 70%; } 

    I took the flexbox aligner styles from Philip Walton’s Github. I started using CSS back in version 1, so I’m still not used to this flexbox voodoo.

    4. Add the content to the front page widget

    The widget won’t become active until content there is a widget added to it. If you are going to put HTML and Javascript in it, choose a Text widget. Paste your code in there. Here is what I cooked up for our video testimonial box:

     class="two-fifths first Aligner">    class="Aligner-item Aligner-item--fixed">     

    Diana loves Praxis. Here's why...

    "Praxis gave me the skills and experience needed to run a sales team at the age of 18, when the rest of my peers were sitting in classes."
    class="three-fifths">Responsive video embed here

    If you are looking for a great video hosting platform with a ton of options (like responsive embeds and private access), check out Wistia.

    The Result

    This isn’t ready to go live on the site yet because we are working on new videos to put in the block, so here is a screenshot with demo content. You’ll notice that I made the video a little larger than the text box (2/5 vs 3/5) because I wanted the focus to be on the video.

    Diana's demo full width video testimonial box

  • Moving your Jekyll Site to Amazon S3 and Cloudfront with Outside DNS

    Moving your Jekyll Site to Amazon S3 and Cloudfront with Outside DNS

    If you are using a static site builder like Jekyll, Amazon S3 is one of the cheapest hosting solutions around. To speed up delivery time for a little extra cost, I recommend using Cloudfront in front of S3.

    A few months ago I decided to serve my static assets from S3, but yesterday I decided to take the full jump. Here is what I did to make the move.

    This full guide will be most useful for static sites on existing hosting solutions that you are moving to AWS while using outside DNS services. This guide uses s3_website, Amazon S3, Amazon Cloudfront, and a non-Amazon DNS service.

    If you are setting up a site from scratch, use Amazon’s guide instead.

    0. Back up your stuff

    The steps below worked for me, but I can’t guarantee everything will work for you. Back up your stuff so you can roll back. You’ve been warned.

    Really, before you make a mistake and mess a bunch of stuff up, make sure you have a back up of everything:

    1. Set up your AWS account

    Set up an account at Amazon Web Services.

    2. Download and configure s3_website

    s3_website is a very useful tool for automatically setting up buckets on S3 and a Cloudfront distribution to host a static site. It also helps easily deploy updates to your static site with a few commands.

    Follow the tool’s instructions on Github.

    Handling non-Jekyll content

    If you have content on your webserver that doesn’t exist in your Jekyll site, you’ll need to set some extra configurations for those things in the s3_website.yml. For example, I serve a bunch of PDFs that are separate from my actual Jekyll instance. If you do, too, make sure you take advantage of the ignore_on_server section of the configuration. Make sure to uncomment it (remove the # in front of it) and list the folder paths from the root that you want the tool to ignore on the server. Otherwise folders not on this list and not in your Jekyll site will be removed.

    I added these:

    ignore_on_server:   - justanswer   - illum 

    Reminder: Don’t use tabs for formatting in YAML files. Use spaces.

    3. Deploy your website using s3_website

    Run a new build on your Jekyll site: jekyll build

    Then, push up to the AWS environment: s3_website push

    Don’t worry, even though the s3_website.yml gets added to your _site folder, it won’t get uploaded to S3. The tool skips it. I triple checked this because I didn’t want to publish my access keys online.

    Wait 15 or 20 minutes for your site to propagate across Cloudfront (the Cloudfront dashboard shows the propagation status.) Once it does, check your Cloudfront domain (or public S3 domain if you aren’t using Cloudfront). The s3_website tool gives you both domains during your initial setup, or you can always get them from your AWS console at any time. For example, my Cloudfront domain for this site is d27zm8z2abfvhn.cloudfront.net and my S3 domain is http://cagrimmett-jekyll.s3-website-us-east-1.amazonaws.com.

    Check the domains and make sure everything seems to be live and working correctly.

    4. Add your own domain to Cloudfront or S3

    First, add your domain, including the www, as a CNAME on your Cloudfront distribution. This allows Cloudfront to serve requests to this domain once it is point there. This is the easy part.

    Pointing your domain at Cloudfront without using Route 53 as your DNS provider

    I have a bunch of DNS records on cagrimmett.com, so I didn’t want to migrate my DNS over to Amazon’s Route 53. That means I had an hour of trial and error (as well as a consultation from my friend Eric DavisArchived Link) figuring out how to get things to work. Also, the typical A record pointing won’t work because the IP addresses to Amazon’s servers change regularly.

    The solution we settled on is: CNAME the www subdomain to Cloudfront and forward all cagrimmett.com requests to www.cagrimmett.com.

    To CNAME your www subdomain to Cloudfront, just log in to your DNS service and add a new CNAME record for www (or change the existing one if you have it) and point it to your Cloudfront domain, which is the one that looks like this: d27zm8z2abfvhn.cloudfront.net.

    You have two options for forwarding non-www requests to the www subdomain:

    A) If you aren’t using your domain for anything except this site, you can use your DNS service’s domain forwarding tool if it has one. Set it up to forward domain.com to http://www.domain.com. Note: If you are using your domain for anything else or if any subdomains point to the @ record, don’t use this option. I tried this and took down my other sites, which are served from subdomains of cagrimmett.com.

    B) Use Apache or nginx to rewrite requests. This means that you still need your original hosting, but it will only be used to rewrite your domain requests. This isn’t an issue for me because I still need my hosting to serve cooklikechuck.com, amandakate.me, and my dev and staging areas for WordPress development. This option isn’t ideal, and definitely not what I would have designed from the beginning, but I don’t want to burn everything down and start over. So Apache it is. Here is what my rewrite rule looks like in my .htaccess file:

    RewriteEngine On RewriteRule ^(.*) http://cagrimmett.com/$1 [QSA,NC,NE,R,L] 

    This takes any non-www requests and rewrites them to the www subdomain, preserving the whole query string, making sure existing links to your content around the web don’t break.

    Wait an hour for all changes to take affect and you should be good to go!

    5. Deploying updates

    Since we used s3_website, deploying updates and new posts to your site will be super easy:

    Navigate to your Jekyll site folder and build your Jekyll site: jekyll build

    Then push up to the AWS environment: s3_website push

    That’s all!

    A note on SSL

    I opted to not use SSL for my site right now because there are a ton of extra steps and extra cost involved. I’ll probably revisit this later when Google starts penalizing non-secure sites, but for the time being I’m sticking with plain http. I’m not collecting any user-submitted data.

  • 3 Lesser-Known Hubspot Tools

    3 Lesser-Known Hubspot Tools

    Hubspot is an easy-to-use marketing and sales CRM. It is a lightweight alternative to Salesforce and Microsoft Dynamics that has a ton of marketing and sales functionality.

    This week I dug in to it and found some lesser-known features:

    What if your workflow involves emailing contacts to get them to fill out a form, like an Application form? It is annoying for the user to fill out information you clearly already have, such as Name and Email Address. Smart Forms are a partial solution to this problem, but don’t work if people fill out one form on their computer and another on their phone three days later.

    After some digging, I found out that Hubspot allows you to assign information about your contact to variables and append them as query strings on URLs.

    This means you can set up email templates to make it unnecessary for your customers to type information over and over. Awesome.

    Any time you drive someone to a form via email, you should use query strings to automatically fill things for them.

    COS URL redirects

    Hubspot’s Content Optimization System (COS) is essentially a landing page and content platform hosted on Hubspot. You usually set it up on its own domain or subdomain and it is useful for tracking user interactions. Let’s say you are no longer using a COS page, but it is linked somewhere and people keep hitting it. What do you do?

    I found the solution buried a few levels deep into the Marketing platform. There is a URL redirect tool built in.

    Leverage connections to other apps via Zapier

    Hubspot connects with Zapier, so it connects automatically with 750+ apps. New contacts, contact updates, calendar tasks, social media messages, and form submissions can kick off workflows.

    For example, you can:

  • Jekyll Tools

    Jekyll Tools

    Back in the summer of 2015, I decided to trash my website and rebuild it from scratch on top of Jekyll, a static site generator.

    My goal was two-fold:

    1. Build a new, fresh website to house my personal brand.
    2. Learn the Liquid templating language.

    I found a starter theme, gutted it, and spent a week digging in to how Jekyll works in order to build the features I wanted. Along the way I built out some tools and templates for myself and decided to share them on Github.

    The collection so far: