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.

Vindication!

I already mentioned this in an addendum to my last blog post, but it seems to warrant its own dedicated post.

I’m a self-employed, solo developer, not very actively engaged in the WordPress “community” even though my work is 95% WordPress. So I have apparently missed the memo that shortcodes were (prior to yesterday’s release of WordPress 6.2.1, anyway) the way people were injecting PHP into their HTML-based Block Theme templates. (Silly me… I was just misusing Block Patterns to the same effect.)

Well… as it turns out, allowing shortcodes in Block Theme templates apparently was a security issue, which the WordPress core team summarily “fixed” by just outright removing shortcode support in templates in this update.

This change did break a pair of sites for me (which are still just in final testing, not live, and which I need to go fix as soon as I finish writing this), but the problem was relatively minor. It sounds like a lot of people are using shortcodes extensively as a backdoor hack for adding PHP functionality to templates, and they are… um… not happy.

At what point does the Gutenberg team collectively take a step back and realize that maybe they’ve been the ones Doing It Wrong™ all this time? I feel like that reckoning is approaching.

A Gutenberg/Block Editor revelation… just stop trying

This is not as defeatist as it seems by the title. I’ve actually had a huge breakthrough in my ongoing battle journey with the WordPress Block Editor (a.k.a. Gutenberg).

My biggest problem throughout the process of trying to build a Block Theme has been finding myself hamstrung by the lack of PHP in a Block Theme’s all-HTML template structure. I’ve ended up brute forcing my way into having access to PHP with a combination of ACF Blocks and Block Patterns. But it should have been obvious to me that both approaches were wrong, because I found myself creating ACF Blocks that didn’t have any custom fields and Block Patterns that didn’t have inserters.

The fact that I was using both of these tools in ways that they are patently not intended to be used should have been my first clue, but the problem has always been that documentation of all of this new technology is so scarce, inconsistent, poorly organized and out-of-date by the time it’s written, that it’s hard to really know in advance how they work, and whether or not you’re using them properly. And as my recent series of blog posts have indicated, I am the proud king of Doing It Wrong™.

But as I said at the beginning, I’ve had a revelation, which is this:

The only reason to create a pure “Block Theme” is if you intend to use the new Site Editor (a.k.a. Full Site Editing).

I emphatically do not intend, now or ever, to use the Site Editor, because I have always coded themes from scratch, and the people I am building sites for do not want to modify the overall design themselves, nor should they be given access to the tools to do so.

I am completely locking down access to the Site Editor on the sites I build, so why should I design my themes to work with it? Well… until now, I kind of just thought that was The Way Forward. Maybe it is, but it’s a way that does not, at all, align with how I do business or what my clients want/expect from me.

Luckily, core WordPress team member Carolina Nymark has written an excellent introduction to using PHP templates in block themes. It’s as simple as this. Just… use the old PHP-style of templates. There are a few tricks to be aware of, most of which are addressed by Carolina’s article, but some more I discovered along the way.

I’ve spent the last year and a half of building my block theme constantly butting up against this frustrating limitation. Now after about 4 hours of work, I’ve managed to convert my nascent Block Theme to using PHP templates.

I’ve eliminated my custom field-less ACF Blocks.

I’ve eliminated my un-insertable Block Patterns.

Things are working like they should. Well, mostly. This is an ongoing process. But the key test of the change has been that everything that was working in the theme before is working now, and I have the full capabilities of PHP and the long history of PHP-based WordPress development back at my disposal for future work.

I’ll write more about this in the coming weeks as I refine my process, including an overview of my general setup for a Block-friendly but PHP-rich base theme.

Update: Well, it seems rather fortuitous that I chose this undertaking when I did, because it coincides perfectly with the release of WordPress 6.2.1 which breaks shortcodes in Block Theme templates (which is even more of a shitshow for some people than it is for me, since it hadn’t occurred to me that shortcodes could be used as a workaround to the absense of PHP in Block Theme templates), including a pair of sites I’m currently developing using this theme. Switching those sites to the new PHP-based version of my theme should fix this issue automatically.

The lengths to which I will go to “Do It Wrong™”

First, let’s get one thing straight: WordPress is built on PHP. The Gutenberg/Block Editor team may love React more than anyone else outside of Facebook, but ultimately WordPress is still built on PHP, and the WordPress developer community is built of PHP developers.

It doesn’t have to be PHP. I mean, PHP is kind of a garbage language if I’m honest. But the point is, there is server-side processing happening. It is what makes it possible to dynamically assemble page output, and create separate data, functionality, and design layers in a web application. But for reasons I barely understand and certainly do not agree with, the Gutenberg team decided to make templates pure HTML. No PHP allowed. I feel like they’ve separated the wrong layers.

Anyway, the problem I’ve run into here is that I have perhaps become a bit too dependent upon the one place in Gutenberg where you can still write PHP: block patterns. Block patterns are PHP files, not HTML files like templates or template parts. So naturally I’ve been tempted to misuse block patterns. (Although it didn’t really become apparent to me that I was misusing them, until I was past the point of no return.)

I have always used Advanced Custom Fields extensively in my WordPress site development. And in the Gutenberg era, it’s made it possible for me to create custom blocks while still working primarily in the familiar world of PHP.

I’m getting better at creating block patterns, but today I discovered a way that I may be fundamentally misunderstanding them. I’m really kind of using them as template parts, I guess, but as a cheat way to get access to PHP. Specifically, I’ve been putting block patterns into my templates. Not as ways of dropping in a pre-formatted set of editable blocks in the Block Editor itself, but as “hardcoded” ways to include some PHP-driven elements in the non-editable parts of my page templates.

This has all been working perfectly well until today, when I decided I wanted to be able to drop the contents of an old-school ACF field into a block pattern I created. This pattern is for displaying some of the meta data about a post: post date, categories and tags, and now a new custom field: the byline.

Don’t say I should just use author fields; if you don’t understand a context where a news post might have an author who is not the person who is entering the post in WordPress (and who, in fact, does not even have a WordPress login) I don’t know what to tell you.

I figured, OK, this will be a no-brainer. I’ll just put this into the block pattern PHP file:

the_field('byline');


Oops… that didn’t work. Let’s try this:

the_field('byline', $post);


Hmm… still didn’t work. Oh sure, I need to get the global variable first:

global $post;
the_field('byline', $post);


Wow, that doesn’t even work. Well, what about this?

the_field('byline', get_queried_object_id());


Take a guess.

So, here’s the problem. Block patterns have no context. When a block pattern gets inserted into a page, then it does have context. So if I were to go and edit the post, and insert this block pattern into the actual post content, then it would display the data. (I guess… I didn’t try that until several steps later.) But that isn’t what I want. I don’t want the client to have to remember to insert this “post meta” block pattern at the top of every post. I want it in the template. That’s the whole point.

But if the block pattern is directly in the template, it doesn’t know the current post ID. More importantly, it has no way to even access the current post ID. I’m Doing It Wrong™.

Fine, I know I’m doing it wrong. But once again I feel like WordPress itself is fundamentally wrong here.

And I’m determined to do it my way, even if it’s “wrong,” dammit.

After probing several further layers deep on this (including trying to use the ACF shortcode in the block pattern — which is where I realized it does work if you insert the block pattern into the actual post content, but not in the template), I determined that there was really only one way to do it wrong that still actually works.

I created a custom ACF block designed solely to just output the value of any arbitrary custom field.

This is so unbelievably WRONG I can taste it. But it’s the only way I’ve found to do what, in all of my experience across nearly two decades of working with WordPress and PHP in general, seems like it should be a really freaking easy thing to do.

So, please, DO NOT UNDER ANY CIRCUMSTANCES DO WHAT I AM ABOUT TO SHOW YOU HERE. You’ve been warned.

OK. First, you need to have Advanced Custom Fields Pro installed, so you can use ACF Blocks. In your theme’s functions.php file, do this:

register_block_type(dirname(__FILE__) . '/blocks/acf-diw');


Then you need to make sure you have this hierarchy of files in your theme:

blocks/
	acf-diw/
		acf-diw.css
		acf-diw.php
		block.json


We’re not actually going to put anything in acf-diw.css at this point, but you might want it later.

Here’s what goes in the block.json file:

{
	"name": "acf/acf-diw",
	"title": "ACF DIW",
	"description": "",
	"style": "file:./acf-diw.css",
	"script": "",
	"category": "",
	"icon": "editor-code",
	"apiVersion": 2,
	"keywords": [],
	"acf": {
		"mode": "preview",
		"renderTemplate": "acf-diw.php",
		"postTypes": []
	},
	"supports": {
		"inserter": false
	},
	"styles": []
}


Then in your acf-diw.php file you need this. Note this is the absolute bare minimum code you need for this to work; I would recommend actually using the get_block_wrapper_attributes() function to allow you to include CSS classes, styles, an ID, etc. in the output — and my actual version does have that. This is just to key you in on what specifically makes this trick work. It’s not highly secure, but I think it’s reasonably safe, specifically because we’re checking to make sure we’ve passed in the name of a field, and that there’s actually a custom field on this page/post with that name, and we’re sanitizing the output.

<?php
global $post;
if (!empty($block['data']['field']) && $field_value = get_field(esc_attr($block['data']['field']), $post)) {
	echo '<span>' . wp_kses_post($field_value) . '</span>';
}


OK, now with all of that in place, here’s what you can put into a block pattern file and actually get the output of an ACF custom field that exists on that page/post:

<!-- wp:acf/acf-diw {"name":"acf/acf-diw","data":{"field":"byline"}} /-->


Replace “byline” with the name of your ACF field.

It works. But you didn’t hear it from me.


Side note: This does not work properly when it’s actually inserted into the page content as a regular block. As configured, it is strictly for use in block pattern files where you want to break what block patterns are apparently intended for. (That’s why we have the "inserter": false line in the JSON file.) You could build this in a way that would make it work properly as an inserted block, but why bother? That is, expressly, what the ACF shortcode is for.