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.

WordPress challenge of the day: sorting by meta value, including posts WITHOUT that meta value set

I dug around quite a bit for a solution to this today, and eventually I found one, even though it’s a bit ugly.

The problem here is in setting up a WordPress query that sorts posts based on a meta value. I wanted to sort a list of pages by template, but I wanted to include all of the pages, even ones that don’t explicitly have a template set. But the default query was only showing the ones that did have the template value.

Several dead ends almost led me to give up, until I realized it was a JOIN issue. Specifically, the need to change an INNER JOIN to a LEFT JOIN. I just needed to figure out how to do that in the context of WP_Query.

Cut to the chase, here’s what I ended up with.

add_action('pre_get_posts', function($query) {
  if (!is_admin()) { return; }
  $orderby = $query->get('orderby');
  if ('_wp_page_template' == $orderby) {
    $query->set('meta_key','_wp_page_template');
    $query->set('orderby','meta_value');
    // Workaround to include items without this meta key
    // Based on: https://core.trac.wordpress.org/ticket/19653#comment:11
    add_filter('get_meta_sql', function($clauses) {
      $clauses['join'] = str_replace('INNER JOIN','LEFT JOIN',$clauses['join']) . $clauses['where'];
      $clauses['where'] = '';
      return $clauses;
    });
  }
});

I don’t like doing a str_replace() on part of the pre-built query, but sometimes you gotta do what you gotta do. Also note that this is part of a larger function I am writing that is only for use in the admin side; you could remove that is_admin() check if you want this to work everywhere.

I haven’t had a chance to dig into the details of the query to figure out why the original source post included moving $clauses['where'] into $clauses['join'], but it’s essential. I tried skipping it, and it didn’t work.

Sorry I can’t provide any more context here… but I hope it’s helpful to anyone who finds themselves in a similar situation!

How to REALLY check if the content is empty in WordPress

Problem: You want to check if the content in a WordPress post is empty. Seems easy, but do a Google search on the topic and you’ll see the question asked and — incorrectly — answered several times.

The fact is, I know how to do this. I was just hoping there was a built-in function in WordPress that I didn’t know about. Apparently not, so I wrote my own.

Why isn’t it easy and obvious how to check for the content being empty? Well, you could do this:

if ($post->post_content == '') { ... }

That will work. If the content is really empty. That means a zero-length string. As in strlen($post->post_content) == 0. Which it might be. But probably not.

If you’ve worked with real world site content, or even someone else’s Word documents before, you know that blank space is invisible, and a lot of times there’s a lot of blank space in a document that is not truly “empty.” Spaces, line breaks, HTML paragraphs with nothing but a non-breaking space in them. It all takes up space, and makes the content look empty, even when it’s not.

That last example is the critical one here. A WordPress post may look like it has no content, but if someone pressed Enter while the cursor was in the content box and then saved the page, it most likely has at least one <p>&nbsp;</p> in it.

So what you need is a function that takes all of that invisible cruft into account. Since it doesn’t seem like WordPress has such a function built in, I wrote my own, which I have made as compact as possible:

function empty_content($str) {
    return trim(str_replace('&nbsp;','',strip_tags($str))) == '';
}

This function takes the string you pass into it, strips out all HTML tags, then removes any non-breaking space entities, and then trims all whitespace. If there’s nothing but that stuff, then it becomes an empty string. If there’s any “real” content, the string won’t be empty. Then it just compares whatever it has left against an actual empty string, and returns the boolean result.

So now if you want to check if the WordPress content is really empty, you can do this:

if (empty_content($post->post_content)) { ... }

This will return true if the content is empty; false if it’s not.

Update (8/31/2017): This post continues to be one of the most frequently viewed on my blog, and I’ve been meaning for ages to amend it with this important note. As written here, you’ll get an erroneous true returned if the only content is in HTML, for instance, an image. If you want the function to return false if there’s no text content, then leave it as-is. But you can add a second input parameter to the strip_tags() function to tell it to leave certain HTML tags alone. If you want to allow image tags, for instance, the modified code would read as such:

function empty_content($str) {
    return trim(str_replace('&nbsp;','',strip_tags($str,'<img>'))) == '';
}

How to really exclude the home page in the WordPress wp_page_menu() function

I’m posting this little tip for my future self as much as for anyone else.

The problem: It seems that in recent years WordPress has all-but-deprecated the wp_page_menu() function in favor of the wp_nav_menu() function, but the latter is primarily intended for Custom Menus, and there are some cases where Custom Menus aren’t what you want.

I’m working on a couple of sites right now that have a lot of pages, and I don’t want their editors to have to go over to Appearance > Menus every time they add or move a page. I’m relying on the CMS Tree Page View plugin on these sites to allow the clients to leverage the built in Parent / Order settings on pages to manage their primary navigation, rather than managing a separate Custom Menu.

Since I’m not using a Custom Menu, I don’t want to use wp_nav_menu() at all; I pretty much have to use wp_page_menu(). Which is fine. Except for the fact that the site designs do not call for having Home in the navigation.

No problem, right? After all, I can just add 'show_home' => false to the arguments passed to the function, and it will remove the home page.

But it doesn’t.

I’m not entirely sure what’s going on in the WordPress core here, but I suspect that show_home only works if you’re using the old school default configuration of WordPress that calls for the home page being the main “posts” page. And who does that anymore? If you’ve created a custom home page, even if you’ve configured WordPress properly to display it as the main page, this function doesn’t care. (Do functions “care” about anything? But I digress…)

Remember also that there’s an exclude argument, to which you can pass a comma-delimited string of post IDs to exclude. That works, but… ugh. You mean I really have to hardcode the post ID of the home page right into my header.php file?

Of course not. Use this: get_option('page_on_front') and it will automatically find the home page. This is great if you want to be able to reuse a theme or custom function on multiple sites or just not commit the transgression of hardcoding something that really doesn’t need to be hardcoded.

Here’s the complete code sample. Note there’s no need to bother with show_home at all.

wp_page_menu(array(
    'exclude' => get_option('page_on_front'),
));

Overriding WooCommerce (or any WordPress plugin) functions: a semi-solution

Here’s a question I’ve spent the past few days dealing with based on an issue a client had. How can you override a function in the WooCommerce core? The simple and dismissive answer is, you can’t. I tried a lot of different possible solutions. Eventually you may just be able to track down a solution that works in your specific case, but there’s no general rule that works universally. In this post I am going to discuss the specific problem that was the impetus for this journey, explore some of the challenges the situation presents, and describe the ugly but marginally tolerable solution that worked in this one narrow case.

What’s the problem?

Why would you ever want to override existing WooCommerce functionality? Well, maybe I need to start with a simpler question. What is WooCommerce? It’s a plugin for WordPress that adds extensive e-commerce capabilities. It’s hugely popular and, for the most part, really good. But it’s not perfect, and it’s not right for every possible scenario.

We have a client with a huge number of products, and a huge number of variants of those products. Sizes, colors, styles, etc. And as it happens, this client doesn’t give all of those variants their own SKU. But they do give some of them a SKU, and sometimes multiple variants share the same SKU.

Don’t get all principled about the definition of a SKU. They’re totally arbitrary and different businesses will use them in different ways. It’s not my job to police my clients’ SKU conventions, just to give them a way to use them within WooCommerce.

So now, here’s the problem. The client had been able to give multiple variants the same SKU. But a couple months back, we ran an available WooCommerce update, and it “broke” this “feature” for them. As it happens it was really fixing this bug in the system that allowed variants with duplicate SKUs. At least that was the argument in favor of the change. Even though I agree with coenjacobs who wrote: “I can think of use cases where this might be expected behaviour. Variations don’t necessarily require a product to be completely different, therefore duplicate SKUs might be required.”

Yes, I can think of use cases like that… my client’s website! Unfortunately there’s no turning back, so we need to find a solution.

The solution, on the surface, is extremely simple. Inside the WooCommerce plugin there’s a deeply buried file called includes/admin/meta-boxes/class-wc-meta-box-product-data.php that has this bit of code at line 1547:

$unique_sku = wc_product_has_unique_sku( $variation_id, $new_sku );

That code happens inside a method that saves variant data. It’s calling a function that checks that the SKU on the variant is unique. This block of code was apparently added in version 2.1.12 of WooCommerce. All you really need to do to “fix” the problem and restore the old functionality that allowed duplicates is to comment out that line of code, and replace it with this:

$unique_sku = true;

(OK, technically it would probably be better to write another function that makes sure that the SKU is unique in the system except within variants of this particular product, but that’s a topic for another day… or at least a passing mention again at the end of this post.)

I put “fix” in quotation marks up above because, trust me, you’re not fixing anything by editing the core files of a plugin directly. You’re just setting yourself up for future problems. Next time there’s an update, and a well-meaning person runs it — say, oh, I don’t know… you — your changes will get wiped out. You need a way to make your changes somewhere else. You need to be able to override this functionality without changing the plugin itself. This is WordPress 101, people. Maybe you need a refresher course. (It’s all ball bearings nowadays!)

What makes this so difficult?

As it happens, there are a number of exacerbating factors that make fixing this particular problem in a safe way incredibly challenging.

1) PHP doesn’t let you override functions that have already been declared. If it did, I could very easily just redefine wc_product_has_unique_sku() in my own way, a way that does mostly what it currently does, but with the added allowance for duplicate SKUs for variants of the same product.

One potential solution I tried pursuing, even though I knew it wouldn’t work, was to “redefine” the function inside an if (function_exists()) conditional. This is a fairly common feature of WordPress and some plugins that is called making functions “pluggable”. The idea is that if you declare your function inside that conditional, and it’s already been declared somewhere else earlier, no problem. Files inside your theme are loaded first, so this allows you to write your own versions of pluggable functions and override the defaults.

But this “pluggable” conditional has to be in the core files in order to work. I can’t put that conditional into my functions.php file, because either it loads after the plugin (it doesn’t, but bear with me for sake of argument) and doesn’t do anything, or (as it actually happens) it loads before the plugin, declares the function, and then when the plugin loads PHP throws a fatal error.

Like I said, I knew this wouldn’t work, for the exact reasons described above. But I tried it anyway. Guess what. It didn’t work. Fatal error. Moving on…

2) WordPress offers “hooks” to allow you to override functionality, but only if that functionality uses a hook. Not every function call in WordPress, or in plugins, uses hooks. A lot of them do, and that’s great. But the call to wc_product_has_unique_sku() at line 1547 in the save_variations() method of the WC_Meta_Box_Product_Data class, found inside that aforementioned class-wc-meta-box-product-data.php file, does not. At least not directly. So the only way this solution will work (hint, hint) is if you can find a place farther up the logic chain that does.

3) The one way PHP does let you override functions is through a PECL extension that is probably not installed on your web server. If I were hosting this client’s site myself, on my own server, I’d just install the necessary PECL extension so the override_function() function was available to me. But I’m not, so I can’t.

4) As designed, WooCommerce only allows you to override files inside its templates subdirectory. You may see a lot out there about solving all of these kinds of problems I’m describing by simply creating a woocommerce directory inside your theme and replicating files from WooCommerce there. Yeah, you can do that, and it works great. As long as the file you’re trying to override is in the templates directory of the main WooCommerce plugin. Anything else is untouchable. Trust me. I tried.

But… you said you found a solution, right?

Yes. I did.

Well… what is it?

You’re not going to like it.

A solution is a solution. C’mon, just tell me!

OK, fine. I found a solution that is ugly and messy, and only works in my specific case. And it’s not at all the kind of ideal “replace this function with my own” solution I wanted.

I did a manual backtrace-of-sorts on the functionality surrounding line 1547 in class-wc-meta-box-product-data.php to see if I could find an action, somewhere, that I could hook into. And I did. But it isn’t pretty.

You see, like I said, line 1547, the one and only line in the entire body of WooCommerce that I want to change — I don’t even want to edit the wc_product_has_unique_sku() function because it’s necessary elsewhere; I just want to not run it right here — is deeply nestled inside a delightfully complex method called save_variations() that weighs in at 263 lines of code. What’s worse, this method is only called in one place in the entirety of WooCommerce, and that’s in the save() method within the same file. Guess what… the save() method is 434 lines of code. Yikes.

Next up, I needed to find any places in the WooCommerce code base where that method appears. And as it happens it only appears in one place… and it’s an add_action() call! At last, we have a hook!

In the file includes/admin/class-wc-admin-meta-boxes.php, at line 50, we have the following:

add_action( ‘woocommerce_process_product_meta’, ‘WC_Meta_Box_Product_Data::save’, 10, 2 );

That’s it. One static instance of the method, inside an action. That’s something we can use, but… oh, no. Does that really mean… but wait, you’re sure there’s… uh… oh.

Yes, we can override this method by creating our own class that extends WC_Meta_Box_Product_Data, and then removing this action and replacing it with another one that runs the save() method inside our class instead. And we can change anything we want inside that save() class. And it will work. I tried it.

But it means we have to replicate all of the rest of that code inside our custom class. We don’t have to replace any of the methods of the parent class that we’re not changing. But we have to replace both the save_variations() method and the save() method that calls it, because at line 1442, there’s… this:

self::save_variations( $post_id, $post );

That self means that if we just change save_variations() in our class, it’ll never run. We need to bring over the entirety of both of those methods into our class — all combined 697 lines of code — just to replace that one line.

That said… it does work. And it’s safe from future WooCommerce plugin updates. As long as nothing else in those two methods gets changed.

Practically speaking, it means remembering before every WooCommerce update to do a diff on class-wc-admin-meta-boxes.php between the new version and the version you’re currently running, then making sure any changes that appear in those two methods get copied over into your child class.

Is this really any better than editing the core and just remembering to redo your change every time there’s an update? I think you could argue that it’s not, but I’ll still say it is, because at least your code won’t disappear when the update gets run. Something still might break… but if this file hasn’t been changed, it won’t. Editing the core file directly guarantees your fix will break when an update runs, and it’s much harder to get your code back. (Hope you kept a backup.)

Let’s put it all together

Now that you’ve seen what we need to do, let’s do it. This goes into your functions.php file in your theme, or, as I have it, into a separate file that gets include()’d into your functions.php file.

<?php

class My_WC_Meta_Box_Product_Data extends WC_Meta_Box_Product_Data {

  public static function save( $post_id, $post ) {
    // Yes, put the ENTIRE WC_Meta_Box_Product_Data::save() method in here, unchanged.
  }

  public static function save_variations( $post_id, $post ) {
    // Again, the ENTIRE WC_Meta_Box_Product_Data::save_variations() method goes in here,
    // unchanged EXCEPT for this line, which you comment out and replace with the next:
    // $unique_sku = wc_product_has_unique_sku( $variation_id, $new_sku );
    $unique_sku = true;
    // Everything else that came after in the original method goes here too.
  }
}

remove_action('woocommerce_process_product_meta', 'WC_Meta_Box_Product_Data::save', 10);
add_action('woocommerce_process_product_meta', 'My_WC_Meta_Box_Product_Data::save', 10);

?>

Well, that’s profoundly unsatisfying

I agree. This is not the solution I was looking for. I’m sure it’s not the solution you’re looking for. But for now at least it seems like the best only way.

What I would really like as a solution requires changes to the WooCommerce core:

1) This would really be great: a checkbox option in the WooCommerce settings to allow duplicate SKUs for variants. I built my own CMS and used it for almost every project for years before fully embracing WordPress as a general purpose CMS. Eventually, it got to a point where some clients were asking for functionality changes that might conflict with ways other clients were using the system. Any time I introduced a significant functionality change, even if it was fixing a “bug” that some clients might assume was a “feature”, I always set it up as a configurable option in the system, with the default setting being the way it already was.

2) Not as great, but this would still help: all WooCommerce functions being made “pluggable”. If only the declaration of the wc_product_has_unique_sku() function inside wc-product-functions.php were wrapped inside an if (function_exists()) conditional, I would be able to write my own version of that function that allowed duplicate variant SKUs. In fact that would be a much more powerful solution than what I’ve done, because I could write it to make sure the variants’ SKUs were only duplicates within the same product. I haven’t tested it thoroughly yet, but I’m pretty sure my actual solution will do nothing to prevent duplicate SKUs for variants of different products, as well as the same product.

Here’s hoping someone with commit rights on the WooCommerce project sees these suggestions and acts on them. In the meantime, I’ll have to live with my convoluted solution. I hope this helps shed some light on ways you might be able to find your own way around this sticky problem.