WooCommerce code snippet: add customer IP address to admin Orders page

First off, this is not solving a problem. It’s making it easier to deal with the fallout of the problem.

Here’s the problem: bad actors steal credit card numbers, and sell batches of those credit card numbers to other bad actors who like to find ways to test out the credit card numbers to see if any are still active.

One way they like to do this is to find WooCommerce sites that sell cheap products — especially stickers, which are generally priced at $5 or less — and they use a script to spam the site with fake orders… well, real orders… for these cheap items, using fake contact information and the stolen credit card numbers. Most of them are already canceled and the transactions fail, but a small percentage of the cards are often still active, and the ability to place an order with them confirms it. I suspect the reason they place very small orders is that it’s easier for those transactions to go unnoticed by the real card owners.

Anyway, this is a problem I am seeing with increasing frequency on my clients’ WooCommerce sites, and there are generally two ways I address the problem.

First, I install Brian Henry’s WooCommerce Checkout Rate Limiter plugin. This can be very effective at throttling the scripts that place these huge blasts of orders from the same IP address, which leads to…

Second, I get the fake orders’ IP addresses and block them in the server’s firewall. You can get the customer IP address of any order in WooCommerce by clicking through to the detail page for an order. There are various ways to block IP addresses, including WordPress plugins, but I like to go straight to the source and block them in the ufw firewall right at the Linux OS level.

But the bad actors are perhaps becoming aware of these techniques to block them, and are modifying their tactics. I can see three ways they would do this, although I am only personally able to observe two of them: 1) slowing the rate of submissions, 2) spreading the submissions across multiple different sites, and 3) using different IP addresses. The first and third are the ones I can observe, of course, unless by chance the multiple sites are all maintained by me. (I do support a very large number of client sites, but not enough that this has happened yet.)

Anyway, we are now getting to the point of this post. I wanted a way to quickly see the customer IP address for a whole list of orders, instead of having to click through to each individual order’s detail page. Sure, I could fire up phpMyAdmin and do direct SQL queries, but I prefer the convenience of having this happen right within the WordPress admin. And so, I present to you a code snippet that will add an IP Address column to the WooCommerce admin Orders page:

add_filter('manage_edit-shop_order_columns', function($columns) {
    $columns['ip_address'] = 'IP Address';
    return $columns;
});

add_action('manage_shop_order_posts_custom_column', function($column, $post_id) {
    if ($column == 'ip_address') {
        $order = wc_get_order($post_id);
        echo $order->get_customer_ip_address();
    }
}, 10, 2);

That can go into your theme or a small plugin. The first block of code adds the IP Address column to the table on the Orders page, and the second block outputs the customer’s IP address in that cell in each row of the table.

Of course, this won’t stop bad actors from being bad actors. But it might help you reduce the number of fake orders your clients have to refund.

The “house of cards” approach to development is a “fatal error” in itself

This morning my work of putting out a fire for one client was interrupted by the need to put out a blazing inferno for another client. Specifically, they’re running a big sale on their WooCommerce store, and the site was returning a fatal error.

Turning on debugging, I saw this message:

PHP Fatal error: Declaration of Dhii\\Container\\ProxyContainer::has($key) must be compatible with Psr\\Container\\ContainerInterface::has(string $id): bool

Ugh.

There is so much about this that I hate. Mainly, what is any of it for? I have to question whether any of the developers of PayPal Zettle POS for WooCommerce, the affected plugin, really know either. This plugin suffers from what I call the “house of cards” approach to development. Why write your own code if you can just slap together dozens of packages that already do the things you want? On the surface, that’s great. But the problem is, then you don’t really know what your own software does.

I recognize that this is a necessity in many cases. It’s just not practical to reinvent every wheel. But when your application is structured like this, you may have 6 different kinds of wheels, or wheels made out of other wheels, or wheels that also contain a kitchen sink. As usual, xkcd nails it:


Fortunately, WP_DEBUG let me see exactly where the errors were occurring, and although my 20 years of idiosyncratic PHP development experience didn’t help me to understand what the error meant, this StackExchange post did. I just had to change this:

public function has($key)

…to this:

public function has($key): bool

And then I had to do that about a dozen more times in various other files deeply nested in the plugin’s vendor folder, until the PHP fatal errors stopped appearing.

In the WordPress support forums, I discovered near the top of the list a post from someone else experiencing this same error, and the devs suggested it was probably a plugin conflict. They didn’t seem interested in pursuing the possibility that their own code was broken.

But, then again, it really isn’t their code. And that’s the problem.

I’m not above reproach here. I’m a WordPress developer. I use other people’s code all the time! I even sell a product that is substantially constructed out of other people’s code. But I am very judicious about what does or does not get placed in my vendor folder. And I realize that if something goes wrong with it, it’s up to me to fix it, even if it’s not my code.

Speaking of which… I have some updates to make. Gotta go!

How to purge fake/bot WooCommerce customer accounts directly in the MySQL database

DANGER! If you don’t know the havoc one can wreak with a DELETE statement in MySQL, stop right here. I take no responsibility for what you might do with the information that follows.


Bots like to create fake customer accounts on WooCommerce (WordPress) sites, apparently. What they’re attempting to do, I don’t know. But if you don’t stay on top of things, you might find you have thousands of fake customer accounts in your site. Chances are they haven’t, won’t, and can’t actually cause any damage, but they’re cluttering things up, and any unnecessary user account in a WordPress database represents a potential future security risk.

On a particular client’s heavy-traffic WooCommerce site, I discovered that over the course of the site’s 7-year lifespan it had accumulated nearly 8,000 such accounts, and I wanted to be rid of them.

After carefully exploring the data surrounding a few of these obviously fake accounts, I determined a pattern, and came up with a fairly cautious set of conditions that, to me, indicated a customer was fake:

  1. They had the customer role.
  2. Their user account had nothing in the First Name or Last Name fields.
  3. Likewise, their user account had nothing in the Billing First Name or Billing Last Name fields. (If you’re feeling extra draconian, you might skip this one.)
  4. They had never placed an order while logged in — their user ID did not have an _order_count entry in the wp_usermeta table. Which is perhaps an obvious condition because…
  5. They had never logged in at all — their user ID did not have a wfls-last-login entry in the wp_usermeta table. This condition will only apply if your site uses WordFence.

You can test all of those conditions with a single SQL query:

SELECT DISTINCT `user_id`
FROM `wp_usermeta`
WHERE
`user_id` IN (SELECT DISTINCT `user_id` FROM `wp_usermeta` WHERE `meta_key` = 'wp_capabilities' AND `meta_value` = 'a:1:{s:8:"customer";b:1;}') AND
`user_id` IN (SELECT DISTINCT `user_id` FROM `wp_usermeta` WHERE `meta_key` = 'first_name' AND `meta_value` = '') AND
`user_id` IN (SELECT DISTINCT `user_id` FROM `wp_usermeta` WHERE `meta_key` = 'last_name' AND `meta_value` = '') AND
`user_id` NOT IN (SELECT DISTINCT `user_id` FROM `wp_usermeta` WHERE `meta_key` = 'billing_first_name') AND
`user_id` NOT IN (SELECT DISTINCT `user_id` FROM `wp_usermeta` WHERE `meta_key` = 'billing_last_name') AND
`user_id` NOT IN (SELECT DISTINCT `user_id` FROM `wp_usermeta` WHERE `meta_key` = '_order_count' AND meta_value > 0) AND
`user_id` NOT IN (SELECT DISTINCT `user_id` FROM `wp_usermeta` WHERE `meta_key` = 'wfls-last-login');

You may want to spot check some of these IDs in the wp_users table, or directly in the site admin, just to be sure everything looks right. Then you can turn the above into a subquery that will delete all of the matching users. Be sure to make a full backup of your database before doing this!

DELETE FROM `wp_users` WHERE `ID` IN (
SELECT DISTINCT `user_id`
FROM `wp_usermeta`
WHERE
`user_id` IN (SELECT DISTINCT `user_id` FROM `wp_usermeta` WHERE `meta_key` = 'wp_capabilities' AND `meta_value` = 'a:1:{s:8:"customer";b:1;}') AND
`user_id` IN (SELECT DISTINCT `user_id` FROM `wp_usermeta` WHERE `meta_key` = 'first_name' AND `meta_value` = '') AND
`user_id` IN (SELECT DISTINCT `user_id` FROM `wp_usermeta` WHERE `meta_key` = 'last_name' AND `meta_value` = '') AND
`user_id` NOT IN (SELECT DISTINCT `user_id` FROM `wp_usermeta` WHERE `meta_key` = 'billing_first_name') AND
`user_id` NOT IN (SELECT DISTINCT `user_id` FROM `wp_usermeta` WHERE `meta_key` = 'billing_last_name') AND
`user_id` NOT IN (SELECT DISTINCT `user_id` FROM `wp_usermeta` WHERE `meta_key` = '_order_count' AND meta_value > 0) AND
`user_id` NOT IN (SELECT DISTINCT `user_id` FROM `wp_usermeta` WHERE `meta_key` = 'wfls-last-login')
);

OK… so the users are gone. But each one has a bunch of records in the wp_usermeta table. Now that we’ve gotten rid of the users themselves, it’s easy to purge their associated meta data:

DELETE FROM `wp_usermeta` WHERE `user_id` NOT IN (SELECT `ID` FROM `wp_users`);

How to make the WooCommerce main shop page show featured products only in 2022

Sorry for the click-bait-y title (especially the “in 2022” part), but I searched fruitlessly for way too long and found too many woefully outdated answers to this. Ultimately what I found still wasn’t quite the complete answer, so I modified it a bit myself to arrive at the following.

The goal here is, as the title suggests, to get the WooCommerce main shop page to only show your featured products. Why this isn’t just a checkbox option in WooCommerce is beyond me. But then a lot of the decisions made by the WooCommerce dev team are beyond me. (Excuse me, Professor Brainiac, but I’ve built e-commerce platforms from scratch and, uh, I think I know how a proton accelerator… oh wait, never mind.)

Anyway, this is it:

add_action('woocommerce_product_query', function($query) {
    if (is_shop()) {
        $query->set('tax_query', array(array(
            'taxonomy' => 'product_visibility',
            'field' => 'name',
            'terms' => 'featured',
            'operator' => 'IN',
        )));
    }
});

What exactly is happening here? Well, as noted by the most helpful resource I found, since WooCommerce 3 (currently on 6.1.1), the “featured” status has been handled by the product_visibility taxonomy, and not by the _featured post meta field. So this needs a tax_query and not a meta_query.

Beyond that, we’re making an extra check that we’re on the shop main page — so this doesn’t affect category archive pages. And we’re using the woocommerce_product_query hook, not pre_get_posts as some other examples suggest, so it only runs on WooCommerce queries and we can skip adding extra conditionals for pre_get_posts to run on, you know, every single post query on every page of the site, including admin.

That’s all there is to it. Now your main WooCommerce shop page will only display featured products, and nothing else changes.

Add arbitrary product data to order items in WooCommerce

This seems to be way more convoluted than it needs to be, but I’m not sure how much of that is that it’s actually convoluted, how much is that Woo’s documentation sucks, and how much is that everyone else’s tutorial on it is tl;dr.

Anyway… I just wanted to do something fairly simple. I want to have each product’s short description get sent into the order data. This is a specific use case with a client who’s syncing data over the REST API with an external system, and we’re shoehorning data into the short description that maybe could go somewhere else. The point is, use your imagination as to how this might be useful to you.

I’m stripping out a lot of the other details. All I want is a way to a) add the data to the item in the cart, and b) carry that data over into the order item meta data in the database. You may need or want more, but this will get you started.

// Add custom order item meta data to cart
add_filter('woocommerce_add_cart_item_data', function($cart_item, $product_id) {
  if (!isset($cart_item['short_description'])) {
    if ($product = wc_get_product($product_id)) {
      $cart_item['short_description'] = $product->get_short_description();
    }
  }
  return $cart_item;
}, 10, 2);

// Add custom order item data from the cart into the order
add_action('woocommerce_checkout_create_order_line_item', function($item, $cart_item_key, $values, $order) {
  if  (isset($values['short_description'])) {
    $item->add_meta_data('Short Description', $values['short_description'], true);
  }
}, 10, 4);

This is a major distillation of stuff I found in these two tutorials: How to Add a Customizable Field to a WooCommerce Product and Add Custom Cart Item Data in WooCommerce.