The simple way to add a “force SSL” option in WordPress

There are plugins for just about everything in WordPress. But cluttering up your site with plugins isn’t always such a great idea. They add bloat that can slow down your site, and if poorly written can cause potential conflicts.

Plus, a lot of them are simply over-engineered. I hate that.

That said, I love good plugins, especially Advanced Custom Fields by Elliot Condon. I consider it essential to every WordPress site I build… which is a lot these days.

A site I’m currently working on has some pages that require SSL encryption. And I want the client to be able to turn SSL on or off on a per-page basis. But I didn’t want to use a plugin (besides ACF) to do it. [Disclaimer: you don’t actually need to use ACF for this; the standard Custom Fields capability will do.]

Before getting started, make sure your site actually has an SSL certificate installed and properly configured. And for this to work as shown, the cert needs to use the same domain name as the site itself. If it’s different, your redirect URLs will be a bit more complicated and will require some customization of this code, but it’ll still work.

First, set up your custom field. I’m using force_https as the field name, but it can be whatever. Make it a True/False field. (If you’re not using ACF, just remember you’ll be entering 0 or 1 as the value.)

Next, in your functions.php file, add the following:

add_action('template_redirect', 'my_force_https');
function my_force_https() {
  if (is_ssl()) { return null; }
  global $post;
  if (!empty($post->ID)) {
    if (!empty(get_field('force_https',$post->ID))) {
      $ssl_url = str_replace('http://','https://',get_the_permalink($post->ID));
      wp_redirect($ssl_url); exit;
  return false;

Picking this apart: We’re using the template_redirect hook. By this point the post has been loaded. We have all of the data we need, and it’s kind of our “last chance” to get WordPress to do a redirect before it starts rendering the page.

First we run the built-in WordPress function is_ssl(), because if we’re already on an SSL connection, there’s nothing to do. (And, if we didn’t do this check, we’d create a redirect loop.)

Next, if we have a post ID, we use the ACF function get_field() to check whether the force_https custom field is checked for this page. If it is, then we modify the page’s permalink to start with https:// and trigger the redirect. That’s it! [Note: If you’re not using ACF, you’ll need to use the built-in WordPress function get_post_meta() instead of get_field().]

Of course, that’s not quite it. You may notice after you have this working that your page loads with an https:// URL, but you’re still not getting the reassuring lock icon in your browser’s address bar. What gives?

Well, that’s because you probably have assets in the page that are loading over a non-SSL connection. In my experience, this is almost always because of images in your content that have a full, non-SSL URL. Browsers won’t give you the lock icon unless every asset on the page was loaded over an SSL connection.

So I’ve added this second function that strips the protocol from any instance of src="http://... in a text string. If you’re not familiar with “protocol-less” URLs, modern browsers allow you to omit the protocol — http:// or https:// — from URLs in your HTML, using just // instead, and the browser will automatically handle those with the same protocol used to load the page.

Using the filter the_content, this will automatically get applied to most page content and you’ll probably be good.

add_filter('the_content', 'my_strip_protocol');
function my_strip_protocol($content) {
  if (is_ssl()) {
    $content = str_replace('src="http://','src="//',$content);
  return $content;

If you add this and you’re still not getting the lock, it means you probably have <img> tags within your theme that include full non-SSL URLs, or possibly some CSS or JavaScript assets that are being loaded over non-SSL connections. You’ll have to troubleshoot that yourself, but with the developer tools built into modern web browsers, that shouldn’t be too difficult. Remember, now that you have it, you can always use this my_strip_protocol() function directly in your theme files as well.

Just a side note about one of my idiosyncratic coding conventions: I always use !empty() when checking for a value that evaluates to true, but you don’t have to. It comes from my prior experience working with CakePHP. The benefit is that you won’t trigger any PHP warnings if the variable you’re evaluating hasn’t been declared.

Who are the changes in Mac OS X El Capitan for? Not for me, apparently

Over at The Loop, Dave Mark commented on Apple’s list of enhancements in El Capitan.

It’s an impressive list. I guess. But it really brought something into sharp relief for me: I don’t use any of the new features in recent Mac OS X updates. I was really tired of Lucida Grande and I prefer flatter design, so the interface improvements in Yosemite and now El Capitan are worth the update alone, as far as I’m concerned.

But it’s kind of sad for me. I’ve realized that my passion for computers and technology has really moved past the “computers” part. I am still a loyal Mac user, and will continue to be for the following reasons:

1. I’m heavily invested in Apple’s “ecosystem” by this point, which is fine with me.

2. Windows sucks. As much as I think Microsoft is trying to improve, and as much as I appreciate Microsoft’s newfound scrappiness as the underdog, Windows still sucks. Especially the licensing process that assumes everyone is a criminal.

3. Linux on the desktop is still half baked, and if anything seems to be getting worse as it becomes clear that it’s never really going to catch on. (That said, I am as devoted to Linux on servers as I am to the Mac on the desktop. But it’s all command line for me.)

As iOS has taken over, I find my Mac is more and more relegated to its “truck” role for me. I still use my Mac almost every day, but only for two things:

1. Work.

2. Music production.

I never play games on my Mac. (Though that might change.) I no longer browse the web on my Mac, except at work. As much as I love the portability of my 11-inch MacBook Air, I might as well just have an iMac at my desk at work, for how often my MacBook Air is ever out of its bag at home.

I no longer even bring my Mac along when I travel for “emergencies”, because there are no work-related emergencies I can’t fix with my iPad, thanks to a trio of awesome apps from Panic. And using the iPad for work is just awkward enough to ensure that I only use it in emergencies, which improves my travel experience.

And at work, I’m set in my ways. I use the Adobe apps, because I have to. I use BBEdit and Transmit. I use Pages and Numbers for documents and spreadsheets, about once a week each. And I use web browsers, for testing my work. I don’t even listen to music on my computer anymore, because I have a Raspberry Pi at the studio running as a “jukebox”.

I hate almost every email interface. They’re so ugly and confusing and useless. I’ve actually taken to using the iPad interface for Gmail in a web browser to check my email, because it’s the least awful. (Want to do that too? Here’s the “secret” link.)

The only built-in features of Mac OS X that I actually use on a regular basis are Safari, Calendar, and Notes. Ah, my beloved Notes. More on that in a minute.

OK, so that brings me back to Apple’s big list of enhancements in El Capitan. Let’s take a look:

I like Automation in principle, and have used it once or twice, but honestly either I’m just clueless or too limited in my use of the computer, but I don’t really see anything I do on a regular basis that could be improved by Automation.

Yeah, I use this, but the new features they’re promoting are really not interesting to me. I guess I lead a boring life. The one thing I do want in Calendar is something they took away… an easy way to enter the time on a new event without having to use the mouse! [Update (10/2/2015): I’ve just discovered the final release version of Calendar does support entering the time when you’re typing the name of the event, the way earlier versions did. Strike this complaint from the record!]

Chinese Features
Japanese Features
Nope. I can respect why these are in the OS and I think they’re important, but they are not applicable to me.

I used the Mac Mail app for years, until it finally got too buggy for me to tolerate anymore a few versions back. Maybe it’s fixed now. I may never find out, because I’m satisfied enough that the iPad interface for Gmail I mentioned above is the least-sucky option available.

Seriously? I tell you what: try printing out a map this app generates. Go ahead. I’ll wait.

See what I mean? Seriously?

Hey, you didn’t actually do it, did you? OK, I’ll show you. If you’re looking at this (already sparsely marked) map on your screen and you hit Print, this PDF shows the absolute non-existent level of detail you get in the printed version. (I especially like the label at the top: “near United States”. Thanks.)

Maybe you’re saying, “That’s not the point… why would you even print maps anymore?” Well, by that reasoning, why would you even look at maps on your computer anymore? As it happens, I had a very specific reason for printing maps. I’m going on a road trip to Utah next week, and I learned the last time I was there that there are huge swaths of the state where you can’t get a data signal. And I didn’t have any printed maps.

This time I want to be prepared. So I was printing out several maps from Google Maps, but their text was small, and the thin gray lines they use for minor highways almost completely vanish when printed. So I thought I would at least try Apple’s Maps app instead. Not only are they inferior, the printed version you get is completely different from what you’re looking at on the screen, with the majority of the text labels entirely missing. What the hell, Apple?! How is this useful to anyone except a 4th grade geography student? (Come to think of it, I have a 4th grade geography student living in my house. Maybe she can fill it in for me.)

Mission Control
I haven’t even taken the time to figure out what this is. I’ll admit I’m still stuck in System 7 when it comes to my approach to window management, but I just can’t fathom why I would need this. It would just add confusion.

Now we’re talking. OK, Notes is one app I genuinely love from Apple. Don’t laugh. I tried Evernote. I tried it for nearly a year. I found it over-designed and slow compared to Notes. I just need a place where I can store whatever random pieces of information come along, and an easy way to search through them to find what I need. Notes does that perfectly. And what’s even better, it syncs flawlessly between my Mac, my iPhone and my iPad. Apple can do whatever other weird crap they want to Mac OS X, just please don’t take away Notes.

I use this to store my photos, by default. But I hate using the app. It seems to be designed for people who have taken less than 100 photos and never plan to take more. Same goes for iCloud Photo Library or whatever it’s called. I find both cumbersome and unusable given that I take probably a dozen photos a day. I just want a place off my iPhone where I can keep my photos, so I can clear room on it for more photos. Now I can’t seem to do that anymore. It sucks.

I realize I’m an edge case here. Any photo I take that I think is worth remembering, I post to Instagram. The rest, I don’t want to trash, but I will probably never look at again. So I don’t need a photo feed on my devices. That’s Instagram. Just take all of the rest away and store them in the vault, please. I have a feeling this is something where I should really seek out an alternative solution, but I haven’t found the time. Suggestions are welcome, but it has to be drop-dead simple or I won’t bother with it.

Ack. I wanted to like Reminders when it was first introduced, but I found it unreliable and more effort than just sending myself an email. I hate email too, but it’s a reliable catch-all place to dump any “action items” that are in front of me. Having to put those into Reminders is extra work, and if Reminders doesn’t reliably, you know, remind me, then what’s the point?

I like Safari. I go back and forth between using it and Chrome as my default browser. Presently I’m in a “Safari phase.” I suppose some of these new features are nice, but honestly it’s only the developer tools I really care about. Fortunately, those are pretty good and getting better.

Split View
This is a new feature that, in theory, I like. But I’m not yet convinced I’ll actually like the implementation, or ever really use it on a regular basis.

Ack. Again. Get this away from me. I never use it. The only times I even interact with it are by accident. I finally took the time to figure out how to disable the keyboard shortcut so I’d stop accidentally calling it up by pressing Command-Space when I’m typing too fast (like right now).

Worse, I have a Mac mini at the studio that is kind of the hub of our network. It’s a file server, VPN server, powers our projector for client meetings, and also runs Parallels Desktop for Windows testing. And it is slow. Really. Unbearably. Slow. I have tried several times to diagnose the problem, without success, until yesterday, I think. It seems the culprit was the system process that scans and indexes file contents for Spotlight. I’m not sure if it was the huge number of files, the handful of huge individual files (Parallels disk images), the server’s Time Machine backup drive, the slow processor, or some kind of genuine hardware defect at work, but so far the system seems much faster since I completely disabled Spotlight on it yesterday.

Which is not straightforward in any way.

OK, so now that I’ve largely crapped all over El Capitan’s marquee features, let’s see if there’s anything interesting left in the grab bag.

New system font: I do like the new system font, a lot.

Find your cursor: this is a great idea, but I find it’s a little inconsistent.

AirPlay video from QuickTime Player: not interested.

Peer-to-peer migration: meh.

Rename from context menu: great, a harder way to do something that’s been around for as long as I’ve used a Mac.

Auto-hide menu bar: do not want.

Copy file path in Finder: oh… hmmm… yeah, I suppose this will be helpful. If I can ever remember that it exists and how to do it. (Hold down Option after opening the context menu? How intuitive!)

Redesigned Disk Utility: sounds good. I’ll have to check it out. Which I will do the next time I am panicked about a hard drive dying and then I’ll hate it because I’m already frustrated about something and I’m not expecting something else new.

Color picker: I suppose.

Rotate annotations: ???

Find My Friends widget: I may use this, but I’m not sure why I’d need to have it on my computer vs. just taking out my phone. The same could be said of Messages, I suppose, but I can type way faster on a real keyboard, so it’s actually useful to get those on my Mac. What benefit does Find My Friends on a Mac offer over the iPhone version?

While we’re on this topic, I’m sure I was not alone when Find My Friends was introduced in saying, “What’s with the rich Corintian leather?” I mean, “When would I ever use this?” I think it’s really the name. Change it to “Find My Family” and suddenly it makes perfect sense. I don’t use it daily, but I do use it at least once or twice a week, and it has proven incredibly handy.

So that brings us to the end of the list, and of my rant. Maybe this has ended up being more of a psychological profile of me than a valuable assessment of the state of the Mac in 2015. OK, it’s definitely that. But I wonder how common I am as a long-time Mac user (bought my first Mac in 1994) who has mostly become disillusioned with the direction of Apple’s software.

Full disclosure: I own a small amount of Apple stock as part of a retirement account I can’t touch until I’m in my 60s. Clearly I am trying to drive up their stock price.

A few thoughts from a nerd who actually DOES care about politics

Jason Kottke linked to a post by David Roberts on Vox today:

Tech nerds are smart. But they can’t seem to get their heads around politics.

This is a great article on nerds and politics, or their lack of interest therein. It addresses a lot of the misconceptions that cloud our understanding of the political landscape in America.

But even as it tears apart the false dichotomy between the two major parties (i.e. they are not “mirror images” of each other), it falls prey to that exact line of thinking with one example it gives.

A voter with one extreme conservative opinion (round up and expel all illegal immigrants immediately) and one extreme liberal opinion (institute a 100 percent tax on wealth over a million dollars) will be marked, for the purposes of polling, as a moderate.

OK, that’s a helpful illustration. Except. There really are people on the right (*ah-hem* Donald Trump) saying we should round up and expel all “illegal immigrants” (don’t use that term) immediately. But there is no one on the left proposing anything even close to a 100% tax on wealth over a million dollars.

It’s hard, even for people trying to expose the lack of a parallel on the left to the extremism on the far-right, to avoid thinking the far-left is populated by crackpots with ludicrously draconian, totalitarian ambitions. But those people do not exist. There is no “far-left” in American politics, equivalent to the far-right.

Even Bernie Sanders, who self-identifies as a socialist — in America! gasp! get me my clutchin’ pearls! — isn’t proposing things like that. The ideas coming out of the left are reasonable and rational, benefitting the vast majority of Americans (at the expense only of those who can easily afford it) while pursuing a progressive goal of greater equality and opportunity for all. They only seem “extreme” because they are so radically different from the course we’ve been traveling on for the past 30ish years.

The real fault of logic here is in assuming that the “center” of current American political thinking is anywhere near the true center of the spectrum of possibilities.

Confession: I wrote this as soon as I hit that “100% tax” line because it aggravated me so much. The rest of the article furthers most of the ideas I’m expressing here, and is far more detailed and well-researched. It is absolutely worth reading, above my rants, but I still think it’s worth calling out this particular example.

In a future post I’ll take on the other big issue I see with nerds and politics: that nerds’ general disdain for politics leads them into a superficial alignment with libertarianism. But that very disdain is also the reason why they don’t explore deeply enough to realize how problematic libertarianism is, and how much it really doesn’t represent their values.

Hey look, new fonts

I’m sure by the time you read this, 5 years from now, I will have changed things 8 to 10 times since writing this, but as of right now… hey, look. Same old site design, but with new fonts!

One new font, actually: Work Sans, in three weights. It’s a great new, no-nonsense but aesthetically pleasing sans serif font that is free which makes it extra nice. (Though I do not begrudge font designers the right to compensation for their work.)

This one initially got my attention by way of a blog post by the great Khoi Vinh. I figured, if he likes it, it’s worth noting.

Album Review: Joe Satriani, Shockwave Supernova

JS_SS_COVER_FINAL_12.75x12.75_rgbJoe Satriani is one of those musicians I’m a little embarrassed to admit that I like. It’s not “cool” to be a Joe Satriani fan. And sometimes when I am listening to his music I cringe a bit myself.

That’s usually why I am embarrassed to like certain music… because at times it’s worth being embarrassed about. Musicians like “Satch” (also embarrassing) generally veer into cheezball territory at least once per album. But in general, people who aren’t music geeks tend to look down on instrumental rock albums and “guitar hero” musicians like Joe Satriani.

But Satch differs from a lot of these “guitar hero” types, in that his songs aren’t just scaffolds draped in virtuosic shredding wankery. He has a great sense of melody and works hard to develop songs with a proper structure. There’s plenty of shredding, of course, but it’s confined to solo breaks in songs that are remarkably “song-like,” despite the lack of singing. (Well, most of the time. He does sometimes sing. But most of his albums are completely instrumental.)

Another big problem I have with guitar hero albums is that there’s usually a colossal ego involved. It’s all about the guitar, and the other instruments are confined to very basic supporting roles. I feel like that’s often the case with Satch too, and to be honest the bass is mostly relegated to the background on this new album, Shockwave Supernova, but the outstanding drumming of Marco Minnemann and Vinnie Colaiuta — two of the best session drummers around — gets almost equal spotlight with the guitar.

Satch sounds amazing, as always. Even better than usual, I think. His precision is unmatched, and he demonstrates a remarkable diversity of techniques and tones. And with this album he even managed — I think — not to produce one single “cringe ballad” that I find myself skipping over. The day I got it, I listened to the album straight through four times and never got tired of it. Even the songs I don’t love have parts I really like, and no song wears out its welcome.

Apparently this is a concept album. As someone who has recorded plenty of instrumental concept albums myself, I can see how it may be hard for anyone other than the musicians themselves to get the concept when there are no lyrics. But then again, the concept is basically an exploration of the stage persona Satch takes on when he performs. So… yeah.

Joe Satriani’s picture is on the cover of every album he has released. I guess that’s commonplace with solo musicians, but it still seems pretty egotistical. And often the cover art just really isn’t very good. But I love the cover of this album, and it’s even cooler when you have the physical CD, because the letters are die-cut out of the cardboard. It becomes an interesting object that is worth owning, instead of another ordinary paper booklet inside a plastic jewel case. Of course I just ripped the CD and filed it away, but I took a few moments to admire it first, which doesn’t happen very often anymore.

Is this Satch’s best album? I’m not sure. There’s a certain sameness to this kind of music, and it definitely is immediately recognizable as yet another Joe Satriani album. But the quality is there. I’d put it in his top 3, and if you’re someone who might be inclined to check out his music (and somehow haven’t already), I think it’s a great place to start.