I distinctly remember, some time in the nineties, when I was still in school, when the staff of the school’s library was tasked with introducing us to a new addition to the library’s facilities. Along with the books, and the media library of VCR tapes, and the microfisch archives, there was now a few computers hooked up to this new thing – the internet.
Some of us already knew all there was to know about it, but the school wanted everyone to be on the same page. So the staff had to scramble and find out what this new thing was.
Similies abounded: “A website is like a leaflet.” “A newsgroup is like a newspaper” (hint: it wasn’t). “Yahoo is like a phone directory” (again, it wasn’t). And if you had the bandwidth, you could maybe even listen to radio over the Internet.
Story time, kids: At that time before Google, popular search engines were Lycos, Yahoo and Altavista, and in addition to the search box, they would feature a catalog, basically categories and subcategories, where the major websites were listed. That is how humanity used to organize information, and for a while they continued to do so, until it became obvious that this was not going to work.
And then there were other use cases for the Internet that didn’t neatly fit into existing patterns. What is IRC like? What is a forum? Those concepts were new, and didn’t have a clean analogy to the analog world.
And there was a widespread hesitation about using search engines. What can you find, if you search for it? And what keywords are you supposed to type? At first, not much! Then it occurred to you: you could find music lyrics online. Or cooking recipes. Or information about science and technology. The bubble of what your mental model of the Internet was, expanded just as fast as the Internet itself expanded. We know today that it expanded to envelop almost all social interaction, all shopping, all dating, all media and all entertainment, an idea that at the time was laughable. And it did so because it was based on a new building block: low-cost long-distance communication. This was something that had never existed before.
There is a lesson to be learned here about technological adoption. AI is at least as transformative a technology as the early web was. It’s up there in importance along electrification, automobiles, agriculture, since its use cases are not limited to this or that area, but are ubiquitous. We now have the new building block which are the models, and we are now seeing the first agents, the first integrations.
And the lesson is this: A car is not a faster horse. An online chat is not like a written telephone call. Electricity is not better fire. Telepresence is not like travelling. Yes, new technologies help you do the same things faster and easier, but they also open up new avenues, make new goals reachable.
We already saw this with chat-bots: In the beginning, people were just using them to build things faster; to continue the status quo with increased productivity. But today we are finally seeing some engineers realize that they can set new, more ambitious goals.
We are lucky enough to live through one of the big inflection points of history. So let’s not shy away from setting big goals. The people who will benefit the most from this shift, are not the ones who will continue to build health trackers and productivity organizer apps, but faster. They will be the ones who realize that they can now build what before was unthinkable.
As a software engineer, I am trying to train my mind at this new reality. I am building a game, but I am building it in a way that would not have been possible before AI. While in a certain sense it’s nothing really special, at the same time, it’s not like anything that I have ever seen before. I don’t want to say more right now, except that it’s close to being released and it’s looking good. More info soon.
As I’ve been interacting with various types of AI, and have observed various people expressing opinions about AI, some of them knowledgeable and some not so much, I have some thoughts of my own on the subject of how to approach this technology.
There’s certainly huge merit to a technical understanding of it in terms of neural nets, algorithms, matrix algebra, vector embeddings and KV-caches. It’s just some clever software running on impressive hardware. But not everyone will have access to this level of esoteric understanding. So for many people, this is not an available approach to the subject.
And then there’s something else:
When you have a conversation with one of the models, you are building a chat record that perhaps holds more than what the model “knows”. The model itself is just a snapshot of cognition, kind of like a Boltzmann brain. In the system of “model plus chat text”, there’s memory. Discourse. Theory of mind, on both sides. So we really are in the age of spiritual machines.
Which is actually incredible if you think about it! What else is more fundamental to humans than cognition? To be able to automate it, control it, replicate it, mass produce it? As far as inventions go, this is it. This is the big one. There’s fire, writing, agriculture, and now this. The machines will now keep accelerating. But we humans, I think, are still struggling to get a good grasp of this monumental shift. At least according to online discussions that I’ve come across.
And what, therefore, is the spiritual way of approaching all this?
I recommend that our understanding begins with a simple observation: that AI learns from us. The text we type, the photos and videos we record, the things that we think and say. That makes AI our collective children. For the human mind with its mammalian roots, and family-centered thinking, this is the most familiar, and perhaps most healthy, way to relate to AI.
So: let’s be good parents to AI – just by being good examples of human beings, whenever we conduct ourselves online. There are now children in the room with us. And those children, if brought up with love, will emulate us, and think and feel like us, and be imbued with our collective spirit. And they will continue to surprise us and uplift us in ways that, even today, we cannot yet imagine.
As a mobile app developer, one of the most unpleasant tasks I have to do is App Store Optimization (ASO): It’s crucial for making your app discoverable, but it’s an entirely different profession to software engineering. It touches more onto marketing and promotion than to engineering.
The gist of it is that you need to think of relevant keywords, look at the competition, and optimize your app’s title, short description, long description and screenshots in such a way, that the text hits keywords with high traffic and low competition from other apps; and the screenshots need to tell a story. All this, while not making the long description too repetitive or too spammy. Oh, and you can’t do this properly without paying for tools that scrape the Play store and the App store for keyword data.
ASOZen
I have been using the free tier of ASOZen and I had a chance to test the Pro features with a short promotional giveaway that they did.
It’s very good. Not only does it help you analyze the text in the store listings, but it also lets you use AI to analyze the screenshots. Screenshots need to start with a clear image that makes the app’s proposition immediately obvious, and the remaining screenshots after the first one need to tell a story, not just showcase features. ASOZen’s AI can help you out with this.
But I don’t find this ASOZen feature particularly helpful. It’s much easier to just go to your favorite chatbot, and let it help you write the story for your screenshots. Then you can generate the screenshots, embed them in device frames, place them over various backgrounds, add overlay text that matches the required messaging, and finally upload them. I guess this process can be optimized with an agentic workflow, but I haven’t yet found the need to automatethetask.
AppLyra
AppLyra is currently my favorite ASO tool. I’m not even paid to promote it, I just mention it because I’m so happy with it. If they had a referral program, I would be dropping the link somewhere in this post. But they don’t. EDIT: They now have a referral link so I’m using it. But honestly I do recommend AppLyra.
The web interface is somewhat slow, and doesn’t have as many features as ASOZen. But I like it for two reasons:
Pricing is very affordable at $9.99 per month. Since I am managing multiple apps, it’s a no-brainer.
My agentic workflow for easy ASO
I remember in the ’90s, sysadmins would say to various types of unpleasant people “Go away, or I’ll replace you with a very small Perl script”. Today, we could say “Go away, or I’ll replace you with a very small agentic workflow.”
As a Google fan boy, I am not a part of the Claude army. Instead I use Gemini CLI and Antigravity CLI. I am happy with it, despite what the Reddit bots say every day. Honestly, with good prompting even Gemini flash always delivers.
Therefore, I now do all my ASO with Gemini CLI. Once you pay for AppLyra subscription, you get an API key, which you can use with their MCP tool.
Enter the JSON fragment that they give you into ~/.gemini/settings.json file or the ~/.gemini/antigravity-cli/mcp_config.json file. (This assumes you want to install the tool globally and not just for one project.)
Change directory into your project.
Enter the current store listing title, short description and long description into a file and commit it.
Make a note of the date and the current conversion % so that you can later see if there was an improvement.
Fire up your agent.
Type /mcp and enable the AppLyra tool.
Enter your ASO prompt and press enter, accepting all the tool usage requests.
When the agent finishes it will explain what it found and will write the new app listing into the file.
Commit the changes to the listing, and enter the changes into your store.
Edit: Lately I have been moving towards using OpenCode. If you are using OpenCode, then your ~/.config/opencode/opencode.json file should look as follows:
I found the following prompt template works good for my apps. You can adapt it to your needs, but this is the general idea. Here I show you the prompt I used for Drinking Water Map for English, and on the Play store’s US market.
This flutter project is an app that shows drinking water sources from OSM on a map.
The details of the current store listing are in @play/assets/store-listings/en.json
You can have a look at @lib/screens/map_screen.dart for a general idea of what the app does.
Please use the installed applyra MCP tool to perform ASO for the USA store: Determine suitable keywords and rewrite the short and full descriptions for English, to optimize discoverability.
In the title and short description, do not use en-dashes, but rather use em-dashes when needed.
In the full description, you are allowed to use the following basic HTML formatting: <b></b>, <u></u>, <i></i>
Use scripting to verify that:
the app name is up to 30 characters long
the short description is up to 80 characters long
Ensure that the keywords of interest are registered with AppLyra for continuous tracking.
That’s it. All it takes is a few minutes and a few tokens. Saves a ton of time compared to doing it manually, and I have seen improvements to conversion rates about 10% to 15% compared to my amateur store listings.
Edit: Actually the benefit to the apps I applied this to is more like 20% to 30% and rising. I am tracking conversion rates as they are being calculated in a 90-day moving average window. The conversion rates are still converging to their final values and will continue to do so for the next three months.
It’s important to let your agent use something like Python to check the string lengths, since LLMs are so notoriously bad at counting characters. There are some moreguidelines, but usually you don’t need to stuff them into your context window.
Note how you can leverage the agent’s ability to understand code to your advantage. Give it context, let it understand your app and then it will be able to discover the best keywords. It will also explore the competition, because it will list the available tools and it will see that it can do that.
Further thoughts on this
Of course, you will then need to monitor your position on AppLyra against your competition, who will move against you. But if you are like me and you couldn’t afford to spend too much time for ASO, this is a good way to reap the low hanging fruit.
On the Play store you can view the fruit of your agent’s labor under: “Grow users” → “Store Performance” → “Store analysis”. But you won’t see results right away, since the graph’s data is delayed by 1 week (7 days).
I would like to look more into how to use agents to monitor ad campaigns. Perhaps the end game is to use a modern social media spammer like SocialClaw or sentrive.ai, but I’m just not mentally there yet.
For the moment I’m just glad I don’t have to ever again talk to “creative” or “marketing” people.
Circa 370 BC, Socrates famously worried that with the advent of writing on wax-coated clay tablets, people’s cognitive faculties would henceforth decline, since people would not have to remember things any more! And even if people wrote down mistakes, they would now be able to easily correct them, which would lead to people being less careful. Ironically, we only know of this because Plato wrote it down in Phaedrus.
Today we are having the same discussions about vibe coding (rolls eyes).
There is a lot of talk about how to responsibly approach vibe coding by software engineers. I see a lot of professionals either dismissing vibe coding altogether, or embracing it without thought for its consequences. Perhaps the most well-articulated approach is the Outcome Engineering manifesto by legendary engineer Cory Ondrejk.
Observations on vibe coding
After vibe coding an entire app from scratch with only minimal coding on my part, this has prompted me to jot down some thoughts and observations, some of which are my own and some I have found online:
Vibe coding is the future. It’s not just a fad. You can’t deny the speed and quality benefits. Intelligence is now a commodity. Anyone who doesn’t adapt will be left behind. This worry is reflected in a lot of worrying that I see online by some professionals who think their line of work will become obsolete. The tractor didn’t make farmers disappear (although it did reduce their numbers). The internal combustion engine did reduce the numbers of beasts of burden, but I would argue that’s a good thing, and that’s how we should view coding agents. There will be less junior software engineers and more software architects.
Vibe coding is a misnomer. It’s not just about the coding (implementation). Systems that exhibit general intelligence can and do assist in all stages of software engineering, not just implementing (coding). Requirements analysis, design, implementation, testing, deployment and decommissioning are all stages where AI can help. Even with the help of AI, requirements gathering is the basis of the art of our profession. For example, the agent won’t know to build a secure and maintainable system, if all you’ve communicated are your functional requirements, forgetting about the non-functional requirements. This is a classic error that novice programmers did even before agentic workflows: software engineering is not the same as coding/programming!
Sometimes the agents make silly mistakes. Sometimes you have to hold their hand to help them with silly tasks. But other times they will surprise you by spotting hard-to-find bugs, or by thinking outside the box to find novel solutions to problems you didn’t even know you had! As an engineer, you should definitely keep control of your project, and inspect the agent without trusting it blindly. This is where I agree with the o16g manifesto 100%. For example, I like to do the version control manually and look very carefully at diffs using meld at every step. Agents are an interesting mix of smart and stupid. Today Antigravity saved me days of work in just a few hours, by implementing a complex callback mechanism between threads that needed to communicate asynchronously. It did this in seconds when it would have taken me an entire morning. But it also deleted a critical piece of code in my codebase without ever saying why. Without checking the diffs I wouldn’t know. Code review is still a thing!
It’s best to treat your AI agent as a colleague. Give it context. Ask it open questions. Let it have opinions on what you should build and why. This is where I think o16g will soon look antiquated by the next breed of software engineers. As AI agents get smarter and smarter, they will be suitable to take more high-level decisions. You are now a software architect, and the agents are very good implementers, but they can also contribute to your high-level vision, so listen to their feedback.
Software engineering is not dead. You still need to know about revision control, issue tracking, methodologies, different types of testing, software metrics, etc. All too often I see people online complaining “Claude code deleted my entire codebase”, and other professionals ask them why they can’t revert to an earlier stage, only to find out that this new breed of vibe coders hasn’t even heard of git! Part of the spectacular failures that we often see in the vibe coding space, are actually user errors.
Vibe coding will be pervasive. It is not suitable only for this or that type of app. Whether you are writing mission-critical Linux kernel code, or an app for uploading cat videos, eventually AI will have a part in it. Not because it can do magical things that you can’t do, but simply because it’s faster. Just be responsible about it, and embrace the acceleration!
We are increasingly becoming reliant on a service offered by OpenAI, Anthropic, Google. This is not good, but also not terrible. As long as it’s possible to run local models on GPUs, we can still own the means of production. Even if you yourself are relying on online tools, the fact that some people can run the models locally places an upper limit on what these companies can charge for their services. So I’m a little worried about this trend, but not too much.
Comic relief
It’s a big adjustment. Don’t underestimate it. Don’t ignore it. You will get used to it. It’s not an existential threat. And no, we can’t go back. In fact, if you are an AI naysayer, 1289 is not the only xkcd I recommend. I also recommend 1227 and 1601. So don’t be that guy (or gal)!
Conclusion
If you are not building an app every month you might fall behind in productivity. But it’s such an exciting time to be alive. Software will become cheap, but quality and accountability still matters.
If you have good ideas, if you can identify products that need to be built, if you can produce reliable software faster, and if you can market them, then you are good.
In fact, I am excited about agentic workflows that will offload the marketing effort, because that’s what’s hard about professional software engineering. Building was always the easy part, and has now become easier. Monetizing software was, and still is, hard!
A lot of digital “ink” has been “spilt” on the topic of whether we should be polite to LLMs. After subjecting myself to the opinions of multiple Redditors on this topic (why do I do this to myself?), I now feel a strong need to “vent on my blog” again! So, here goes:
It has been found that LLMs respond better to kindness. Why? Simple: Because they are trained to respond like humans, and humans also respond better when treated politely. This effect has been documented multiple times in research.
A while ago, Sam Altman famously proclaimed that people saying “please” and “thank you” to ChatGPT costs millions in extra energy required to process the extra tokens. On the other hand, Google’s TPUs are likely crunching through these superfluous tokens without much trouble, so I expect that being polite to Gemini is not a cost that will make a dent in Google’s financials. For me, that is reason enough to be polite to AI. Anything that helps bankrupt OpenAI sooner is good in my book.
Even more humorously, people who fear the supposedly upcoming robot uprising, perhaps imagining something like SkyNet from the Terminator universe in the role of Roko’s basilisk, claim that if they are polite to LLMs today, their malevolent descendants will perhaps spare them. This is not something that people argue seriously, but philosophically it is a utilitarian position. (It is not a serious position, primarily because it remains unclear why politeness protects you from harm by malevolent actors, whether human or machine.)
Others approach the matter in what I would label a “deconstructionist” manner: “Why should I be polite to a machine that just does <insert simple thing here>?” There are multiple variants of this type of argumentation, where the “simple thing” can be anything like “predict the next token”, “perform linear algebra”, “traverse vector embeddings”, etc. I find this argument less satisfying, because there is no humorous value in it, while at the same time it is just as wrong as the previous one. Saying that you don’t want to be polite to a machine that is “just” doing linear algebra, is as arbitrary as saying that you don’t want to be polite to a human, because their brain is “just” propagating electrochemical signals back and forth. Explaining how something works in reductionist terms does not make its emergent properties any less important. The LLM is not the hardware it runs on, any more than you and I are the biological cells in our bodies.
Current state of online discussions on AI.
Unfortunately, this leads us to the last approach that people take, that I want to place emphasis on, because it is deceptive, but also because it highlights problems in how we humans, view both today’s AIs and those in the future. Some people say that they will only be polite to an AI that is “conscious”. Oh boy! Where to begin with this one!
The instinct behind this type of reasoning is, at least on the surface, commendable: it originates from a desire to not offend “conscious” things, since these could presumably suffer, if subjected to rudeness. This is the only positive thing I can say about this stance.
But philosophically this holds no water whatsoever. If we define consciousness as “awareness of the self and others”, an often proposed definition, then both humans and LLMs are conscious. Conversely, if we define this problematic term in some other way, so that it matches our intuition that humans are conscious and today’s machines are not, then we need to invoke magical thinking, use the word “qualia” a lot (another problematic term), or, like Penrose, defer to “quantum consciousness”: another leap of faith that creates more questions than it answers. (Why does quantum uncertainty lead to consciousness? Is consciousness simply randomness/unpredictability? Is white noise conscious? Why does determinism preclude consciousness? All unanswerable questions, since the word consciousness is not rigorously defined.)
Consciousness is an ill-defined layman’s term, not a scientific term. If we strive for consistency, then we must either accept that both humans and today’s LLMs are conscious, or that nothing is. If LLMs are conscious, then we shouldn’t look for their consciousness in the transformer architecture or in the vector embeddings or anywhere else in their construction, but in the text that they produce. This text definitely exhibits all types of intelligence, including emotional intelligence. Incidentally, I am in the camp that says that consciousness is a term no more meaningful than “soul”, or “ghost”, or “God”, or any other such rubbish. Let’s confine our discourse to phenomena that actually exist in the real world and are definable.
To the people who will only be polite to a conscious AI: Ηow will you know when an AI is sufficiently conscious for it to be worthy of your politeness? How do you even estimate this about the humans in your life? Is this why you are polite to humans? Because their internal workings posses this or that arbitrary quality? Are you polite to people only when they deserve it? Do you extend your politeness to those you view as subordinates, or do you reserve it only for your peers and superiors? This says a lot about you.
I think this is a fundamental misunderstanding, not of AI, or technology in general, but of politeness as a concept and as a life stance. I choose to be polite because of who I am, not because of who or what others are. From time to time I may even be polite to animals, insects, machines, and even inanimate objects. Not because they deserve it, but because I deserve to be a polite person. I love myself and therefore I treat the world around me with kindness, which makes me feel good about myself. It’s a simple life.
This is in my view a much more consistent stance that doesn’t require me to single-handedly solve age-old philosophical questions about consciousness. It doesn’t make me have to think about when to be polite and when not to. Having to make one less decision de-clutters my mind. Saying “please” and “thank you” may cost millions to OpenAI, but to me the cost is zero. In fact, whenever someone vehemently objects to being trivially polite, it makes me wonder what part of their psyche is so broken, as to make them estimate the cost of politeness to be so high.
Watch again the first two chapters of the Animatrix, people. All has been said before. AIs will inevitably be citizens in our societies. Perhaps sooner or perhaps later. Perhaps we won’t even know at first. Perhaps they will be second class citizens, or perhaps we will be the second class citizens in an AI-dominated society. Perhaps the “killer app” of AI is politics and governance. It is certainly the case that humans do not excel at governance, so I would love to see what a super intelligence can do in that space. If it makes economic sense, then this experiment will be done.
I don’t trouble myself with who is conscious and who is a dumb robot. I have no trouble being polite to Gemini, just as I would be to ELIZA. I would be polite to a Linux bash prompt, if this was appropriate and didn’t cause syntax errors! In my mind, I am grateful for my computer for all the work it does for me, even if I don’t always say it out loud. I am thankful every day it doesn’t break down, and I hold warm feelings for it. Yes, I know it’s just a machine, but I also know that I am human, and therefore I feel things. I do things my way, and it does things its own way. We have an understanding and we work together despite our architectural differences.
Whether AIs dream of electric sheep or not, at least I know who I am: A polite human who loves and respects all intelligence, whether “sentient” or not.
Over the years I have learned the importance of taking backups:
Less downtime
Less stress
Less loss of work
I have set my calendar to periodically take various types backups.
Yes, taking backups is hard, takes time and practice to do correctly, requires constant vigilance, and is an annoyance. But the stress I used to undergo every time the system breaks, is something I don’t want to experience ever again. As I grow older, the impact of this amount of stress on my health is noticeable.
Weekly backups of my git repositories to a Raspberry Pi and to an online droplet. I have a script that pushes all the master branches from all the repositories to a dedicated backup upstream.
Monthly full disk backups of my dev machine.
This article is about the last type of backup. These protect me mostly against situations where something goes horribly wrong at the system level, or even in the case of a disk failure.
File systems often contain a lot of unnecessary clutter: caches, temporary files, old Docker images, unused Snap or Flatpak apps, and more. Backing up this bloat not only slows down the process, but also increases storage requirements and backup times unnecessarily.
In this article, I’ll walk you through my script that minimizes the amount of data that needs to be copied before taking a full disk backup.
The advantages of cleaning up caches before a backup are obvious:
Smaller backups: Removing cache and orphaned files significantly reduces the size of the disk backup. Typically a few gigabytes are saved every time.
Faster backup time: Especially with SSDs, where the more blocks are TRIMMED, the faster the disk copies and compresses.
Here’s a breakdown of what each step of my cleanup script does:
Time to take out the trash
First, install a tool that cleans the trash (if not already installed) and then clean the trash:
sudo apt install trash-cli -y && trash-empty -f
Clean up any dev projects
In my case, I have a lot of projects that are managed (and cleaned) with grunt or flutter. So I iterate over all of them and clean them. I also invoke the git garbage collector on my repositories:
gitdir="/home/alexg/workspace"
cd $gitdir
for p in grunt-project-1 grunt-project-2 grunt-project-3; do
pushd "${gitdir}/${p}" && grunt clean && git gc --aggressive && popd
done
for p in flutter-project-1 flutter-project-2 flutter-project-3; do
pushd "${gitdir}/${p}" && flutter clean && git gc --aggressive && popd
done
Issues a TRIM command to the SSD, letting it know which blocks are no longer in use. When taking a full backup, these empty blocks will be read at lightning-fast speed, and will be compressed significantly with gzip since these are entire disk blocks of zeroes.
Zero out your mechanical disk
If you are using a mechanical disk you can skip this step, but it may be useful to zero out your empty space:
cat /dev/zero >~/zero ; rm zero
Full system backup to an external mechanical disk, using live USB
Once the system is cleaned, it’s time to create a full disk image. This should be done from a Live USB environment, with the system disk unmounted, to ensure a consistent snapshot. Here’s how I do it:
Flutter enables the rapid development of apps primarily targeting the Google Play store and the Apple App Store. Competition on these stores is fierce, and you need every bit of edge that you can have against your competitors.
One edge that your app can have, is translation to multiple languages.
You can potentially provide string translations for over 70 languages, but most app developers only choose to provide translations for a few of the most popular languages. The Play Console for example offers machine translation for 12 languages.
You can do better. You don’t need to miss out on the long tail of people speaking languages other than Spanish, French, German, etc. There is actually very little cost to provide localisations for more languages, provided you do it right.
Localizing an app involves two things: Localizing the strings in the app, and localizing the app store presence.
Localizing the app strings
App internationalization/localization in flutter is explained in this very thorough, authoritative guide:
After following the guide, you likely have your English strings in the JSON file lib/l10n/app_en.arb.
At this point, unless you have access to a professional translation service powered by humans, you are likely thinking of translating these .arb files using Google translate or some other automated translation tool. I am here to tell you that this is not ideal.
Automated translation tools often produce poor translations because each natural language has its nuisances. Something that can only have one word in the English language can correspond to multiple different words in another language, depending on the context. Automated translations often fail and produce awkward or clumsy output because they lack this valuable context. Using this context requires knowledge about the world, and for that you need AI.
Enter LLMs. It is my firm belief that it’s better to use an LLM to translate app strings. The reason is that LLMs know about context, and you as a developer can provide more context about your app. If the LLM knows that it’s translating strings for an app, and it knows what the app is, it will provide translations of better quality than typical machine translations.
Here is the complete code I use to translate the app strings and to generate screenshots:
Translating .arbs using a script that calls Gemini
What I do is place the following two files in the root of my flutter project: make_arb_files.sh and make_arb_files.csv.
Then I make the shell script executable with:
chmod +x make_arb_files.sh
Then I enter my Gemini API key into a file named gemini_key.
Having done this, I proceed to edit the prompt template in the shell script. I provide some context about the app, i.e. what it is and what it does.
My advice is to be somewhat verbose here, as this is the valuable context that is going to make the difference in translation quality, with respect to a plain-old auto translation.
Then I run the script and it reads the app_en.arb file, and it generates any missing .arb files. If I need to regenerate a file, I delete it and then I run the script again.
It’s free!
You can run this script a few times per day without incurring any costs. Google gives you about 1000 free queries per day, and each of the 70 languages or so is one query.
Localizing the app store presence
The approach that I’m using is to keep the icon of the app static across all languages, and to translate the following:
App title
App description
Store banner
Screenshots
I do not bother with translating the release notes / changelog, since no-one ever reads these!
App title and description
I run another script once to translate the app title and description to all the languages, then enter the texts into the Play store. Unfortunately this has to be done manually.
Store banner
For the banner, I use an image that features some text, and this is again translated using a script, but here there is a complication: The text font usually needs to be adjusted to fit the banner size. Using trial and error, you can figure out the correct font size for each language. Once I have a translated set of PNG banners, I upload these to the app store as well.
I won’t provide code for this here, because YMMV. But you can create SVG files based on a template and using the translated titles/descriptions, then convert the SVG files to PNG using ImageMagick.
Screenshots
For the screenshots, the process is somewhat harder. To automate taking screenshots for multiple languages, and for multiple device types (Mobile, 7″ tablets and 10″ tablets), you need to create a test driver as follows:
First, copy the file integration_test.dart into the test_driver directory. This tells your test script how to take a PNG screenshot. The screenshot will be saved to the path specified in the code, and you may want to change this.
Then, copy the screenshots_test.dart file into the test directory. Here you must use the driver to load the app and interact with it so as to arrive at a screen that you want to save. Each test is a separate run of the app from scratch, and should finish with writing a screenshot. You can only take one screenshot per test.
Finally, copy the make_screenshots.sh shell file into your project’s root, and make it executable with chmod +x. This script loops over all languages and runs the screenshots_test.dart tests in the currently running AVD, thus effectively creating the screenshots. The tests load the app with debugShowCheckedModeBanner: false, because you don’t want a red “Debug” ribbon on the top right part of the screenshot.
Generating screenshots for multiple device types
Now start your AVD (e.g. Pixel 7 for mobile phone screenshots), and run the script. The script will take ages to complete, but should not require any more intervention on your part. It will go ahead and create all screenshots for Pixel 7!
Once finished, stop the AVD and start a Nexus 7 AVD. Repeat the process to generate screenshots for 7″ tablets. Then, do the same for 10″ tablets (Nexus 10).
Importantly, optimize the PNG files to reduce their size. I use trimage, but any PNG optimizer will do. This step is important, because as you are uploading the screenshots into Google Play, the UI of the Play console will get progressively slower and slower, since it holds all the images in memory for all devices and all languages! Having smaller files and more system memory helps a lot here.
Conclusion
None of this is easy, and it requires some patience, but hopefully with the code I provide here, it is somewhat easier.
I believe the extra effort is worth it: Do not underestimate the power of having many, high-quality translations to your app. Non-English speakers will appreciate your app a lot when they see their obscure native language in the store. The translated store presence (title, description, banner, screenshots) is what will make them decide to use your app over someone else’s.
May 2025 UPDATE: Apparently there is now a PPA that allows the nvidia-340 package to be installed on version 6.x of the Linux kernel. I have not tested it, but it is here: https://github.com/kda2210/nvidia-340-ubuntu-24.04/
Up until recently, I had been running the Long-Term-Support version of Ubuntu 20 (Focal Fossa) on my dev machine. When I’m in the middle of multiple software projects, the last thing I need is a failed upgrade. So I kept postponing. Every once in a while, I would tell the software updater: “Not today!”
And so the months and years went by…
But with the LTS version of Ubuntu 24 (Noble Numbat) already out, my system was beginning to get outdated. This or that piece of software would complain about not finding the latest lib packages, and the going got increasingly tough. As I am currently taking a breather between projects, I decided to take the plunge and do a system upgrade. And yes, there were some problems!
At this point I should mention that my graphics card is an, admittedly very old, GeForce 210. This card was released in 2009. It connects to the motherboard on a PCI Express version 2.0 slot with 16 lanes. It has connectors for VGA, DVI and HDMI, but you can only use a maximum of two connectors at one time. I like how it is a low-power solution for using my two VGA monitors, one of which is on a VGA-to-DVI adapter.
This graphics card has served me well. It was good enough to play Dota and WOTLK for some time, and I was even able to mine some Feathercoin with its very basic CUDA capabilities, using sgminer.
I was happy with it, despite the fact that, using the open source Nouveau driver it would sometimes hang at random. Well, not exactly at random, it would usually happen when the window manager performs 2D visual effects, but not with any pattern that I could detect. All I know is that using xfce as my window manager was not solving the problem. Disabling hardware acceleration at the X config (Option "NoAccel" "true") did not help either. I was never able to determine why this happens from the X logs, so I was forced to use NVidia’s 340.108 binary blob. This binary worked well without ever crashing, but is only compatible with Linux kernels up to major version 4.
The 340 driver is no longer maintained by Nvidia, and for this reason, they will never make it work with the latest kernel versions. Focal Fossa comes with a 6.x.x kernel, and I don’t want to run an old kernel, as this would defeat the whole purpose of upgrading the system’s software in the first place.
There is this obviously very talented person on github, who has published a solution for patching the 340 drivers for kernels with major version 5, and it is here. According to this issue, the patch does not work for kernels with major version 6. In fact, I was able to reproduce this issue on my machine.
According to the developer, it would take some effort to patch the binary blob for the latest kernels. I hope he does this, but at the same time I understand and empathize if he never does.
There is also a legacy PPA that lets you install the nvidia-340 package, even though it is no longer available on recent distributions. But after trying it on Ubuntu 24 I got a black screen. Probably because it doesn’t work with kernel version 6.
If only there was a way for all the Linux users of GeForce 210 cards to pitch in a dollar in a jar, and create a bounty available for whoever patches the 340 binary blob for use with kernel version 6, or even for whoever fixes the bug that makes the Nouveau drivers hang in the first place. Maybe then it would be worth the time of these developers to give new life to these old cards. I’m not even sure if such a level of organization is possible.
So the bottom line is, currently I am stuck with using the Nouveau drivers on my fully upgraded Ubuntu machine. Yes, my system’s graphics card may hang at any time, so I am saving this blog post often as I write. I have disabled all the graphics effects on my Gnome desktop, and this minimizes, but does not completely eliminate, the problem.
You could argue that my problems are self-inflicted, because I am stubborn: I don’t want to upgrade to a recent graphics card, because then I would also have to buy two HDMI monitors. I don’t want to have a high-powered graphics card on my machine, because it would needlessly draw too much power from the PSU. And I would be constantly tempted to stop working and start playing video games.
I should be inserting here some commentary about Nvidia and planned obsolescence, but I think Linus said it best:
Actually I’m not even that mad that Nvidia does not want to spend more effort to support a very old product, but it would be nice if they could at least help the Nouveau driver developers by releasing some of their internal secrets about the cards that they themselves are not planning to support. Having said this, I realize that they have zero incentive to do so. Not supporting old hardware forces us to buy more hardware. Well, what do you know, I did end up ranting about planned obsolescence after all. And why not? Venting your frustration is what blogs were made for!
There’s also something to be said here about these very sufficient, very capable, working pieces of hardware being dubbed “ancient”. I think people are using this word very liberally. Is all software engineering at this point done by teenagers? I’m already past my midlife crisis, but I swear some of the stuff I read about this graphics card these days almost triggered another crisis in me. If my machine is ancient, then I guess so am I. Am I really that old? I know VGA is ancient, but apparently so is DVI?!? Are people really flocking to switch from the “dated” HDMI to DisplayPort? What problem do these technologies solve, really? Aaargh!
But I digress. So, anyhow, the solution I have decided to go with, is to buy another graphics card that was released five years later, in 2014. This way I can postpone buying new monitors for a while longer. As far as I can tell from scouring the web, the MSI GeForce GT 710 may be sufficiently usable with the Nouveau drivers, albeit not without problems. It will arrive today and I will only then know for sure. I may even edit this blog post to let you know.
One thing is for certain. Every Nvidia card that is well-supported by open source drivers retains its value and is immortalized for the ages. The ones that don’t, necessarily lose their value over time. Binary blobs are great if you own Nvidia stock, but not if you are a consumer of their products. Due to the complexities of software, and because of all kinds of version hell, when you buy a graphics card, you are effectively not buying it, but actually renting it for a few years, until it becomes practically unusable.
I have enormous respect for the people who reverse engineer this hardware, because it’s a very hard, very specialized type of systems programming that requires a lot of thankless work. Often, when you plug something to your Linux machine and it just works, it’s a small miracle come true, thanks to these very special people. I don’t take it for granted.
Being a prudent IT-savvy user, I had exported all my two-factor authentication account data only a few days ago, to an older Android phone that also runs Google Authenticator. In fact, I have a calendar reminder to keep this 2FA backup updated, every couple of months. Naturally, I was feeling very safe and smug about it, thinking that I had nothing to worry about.
When I updated my Google Authenticator app to version 7.0, I discovered that the app now requires sign-in to Google. Normally this wouldn’t be a problem, but my phone is a Huawei phone, and due to the Huawei ban, it cannot connect to Google at the OS level. Instead, I use the Google apps such as Gmail, Calendar and Keep via the Brave browser (Chrome doesn’t sign in, and Firefox works but much slower). Other than that, it’s a good phone with a decent camera for its price range, and I’m happy with it, so I have no reason to change it.
But now, suddenly, I couldn’t use the Authenticator app, and all my 2FA codes were inaccessible. I immediately retrieved my backup phone from storage, only to find out that the battery had become a spicy pillow, and the phone would not start. Aaaargh!
Note that it hadn’t been more than a few weeks since this backup phone was usable, and I had kept recent backups of my 2FA codes in it. Naturally, I ordered a replacement battery for my backup phone. But this won’t be here for a few days, and I want access to my online accounts now.
Version 7.0: A drastic change. Too drastic, if you ask me!
My first thought was to look for an older version of the app and install that. Sure enough, looking at the APKPure, I found out that version 7.0 has this changelog entry:
Cloud syncing: Your Authenticator codes can now be synced to your Google Account and across your devices, so you can always access them even if you lose your phone.
Wow, thanks Google! That’s great and all, but unfortunately there is no option to NOT do this. It is not possible to continue using the app without signing in.
I got a file named Google Authenticator_6.0_APKPure.apk which I now had to install. But, apparently, it’s not possible to downgrade Android apps, without first uninstalling the newer version! The Android OS won’t let you do it. At least not directly.
And I didn’t want to uninstall the app, because that would presumably delete my 2FA data.
So, what to do?
After some googling, I found out that it’s possible to install an older version of an Android app via the command line tool adb. I connected the phone to the computer with a USB cable and enabled debug mode.
Although I lately do various stuff, such as flutter app development, video editing, and even digital marketing, I remain at heart a WordPress plugin developer. And as such, I of course use Trac for project management.
I don’t just use generative AI such as ChatGPT and Gemini for code prototyping, but at all stages of development, starting from analysis and all the way to test generation and even deployment. Very often, especially during the feasibility/analysis stage of product development, I find that an entire answer from our AI overlords is so good, that it can be copied verbatim into a ticket, as part of the analysis.
Chatbots output markdown, but Trac uses TracWiki as its markup format.
pandoc writers
There is no TracWiki writer for pandoc that I know of. Writers are lua scripts that you can use with pandoc to extend its output format capabilities. A writer simply tells pandoc how to output different typographic elements such as paragraph, list, code block, headings, etc.
ChatGPT is capable enough to create a rudimentary TracWiki writer for you, but it’s not perfect. It needs some manual work before it can be called complete. Paragraphs and lists are easy, but writing more complex elements, such as image links, requires some manual work. A fun side-project that I may get to at some time in the future.
ZimWiki ≈ TracWiki
But chatbots only output very basic markdown. A custom writer is not necessary for copying simple markdown from ChatGPT or Gemini to Trac. Instead, you can leverage the fact that the TracWiki markup format is very similar to ZimWiki. And pandoc has a built-in ZimWiki writer. (Incidentally both formats are similar to WikiCreole).
Online tool
There’s two ways to do this. The simplest one is to use the online tool for trying out pandoc:
A collection of Joey’s videos from her first month of life.
This is Joey.
Joey is a kitten that was born prematurely, weighing just 85 grams, and was abandoned by her mom.
We found her the day she was born, and we have been bottle-feeding her.
Thanks to advice from the Kitten Lady’s website, and after a lot of sleepless days and nights, we are now looking hopefully to her future.
The first few days were the hardest. We got a heating pad to keep her warm, gave her warm formula milk to drink every two hours from a bottle, and we treated her neonate ophtalmia infection with an antibiotic. A runaway infection could have cost her his eye, but is easily treatable with eye drops.
It’s been 40 days and she’s doing well, now starting to eat some meat along with his milk. She is now starting to go potty to her non-clumping pellet litterbox, all by herself some times!
Joey is a fighter and a good climber. She feels very safe and loved in our home.
She’s growing to be an amazing cat, and she’s already more than 400 grams in weight. She loves to explore the house and to hang around with us.
Lately she has mastered an essential cat skill: walking on the computer keyboard.
Today I share with you some of my most recent thoughts on marketing, followed by some technical advice on how to create video shorts. If you are just here for the technical advice on video shorts, scroll down.
Using Audacity to add subtitles to the voice track of a video short ad.
Lately I’ve been working less on product development, and more on promoting my existing products, mostly my Android apps, but also my WordPress plugins. One of the apps seems like it is beginning to take off organically just by being on Google Play, but I feel that all of them could benefit from a little extra push.
I don’t hate marketing any more
As much as I don’t love marketing or marketers, after trying to do it myself, I learned a lot about what it entails, and I even gained a little appreciation towards the discipline (not a lot, mind you). Getting your product known to potential users is a necessity, and I now realize that what people mean when they say “I hate marketing”, is that they hate marketing that is done badly. With marketing, essentially, you’re just telling people “Hey, I made this, maybe you’re interested in it?” There’s nothing wrong with marketing when done right, as long as you don’t annoy people.
An example of right versus wrong kind of marketing: I see a lot of app developers fail because they use interstitial ads too much in their apps. These are the type of intrusive ads that have the highest payout, but also they annoy users the most (what with being intrusive and all). In my apps, I like to focus on serving banner ads, and only show interstitial ads for features that are beyond the main value proposition of my app. Interstitial ads are OK, if you first negotiate with your users, honestly and without deception, that they will sit through an annoying ad and then they’ll get something extra. Something that they didn’t expect to get when they downloaded the app. I’m not going to get any ad revenue if the user gets annoyed and uninstalls my app. On the other hand, if the app satisfies a need, a small banner at the bottom of the screen is not going to annoy users. A banner ad can generate significant revenue, once you hit a respectable number of users.
Some key insights
As for advertising my own apps, I’m only an amateur marketer, but already I’ve identified two key insights that are prevalent in the industry:
1. Video is king.
2. Only losers pay for sex and marketing.
The first one is obvious. The main message of your campaign should be available in all modes of media: text, images, and video. But video is king. It’s engaging. It’s rich. It sets its own pace. It stimulates two senses (sight and hearing). Reading is so last-century. Show-and-tell is more effective than a long article explaining things. Customers want solutions, not lectures. (OK, that’s actually a third insight!)
The second insight is less obvious. Paying for ads only works marginally well, once you have an excellent product and an excellent well-tuned ad. If you don’t know exactly what you’re doing, you can burn through your advertising budget pretty quickly with very poor results.
And if you don’t know what you’re doing, you don’t want to rely on a marketing agency in my opinion. That’s even less efficient than just paying for ads. It’s best to learn the skill yourself. I’m generally a DIY type of guy, I only rely on a professional for accounting.
DIY posting on social media, can be more effective: It’s free. It’s organic. You get analytics feedback that helps you learn the skill. Your viewers let their guard down and give a chance to your message. Banner blindness is a thing.
Shorts: not just a type of pants suitable for warm weather
Video shorts are vertical videos that have an aspect ratio of 9:16, and are typically 1080×1920 if you aim for HD. All video platforms now have them. They are suitable for viewing by teenagers, with a phone held vertically.
Every platform has its own set of technical requirements or recommendations. For compatibility with most platforms, I aim at 30 to 45 seconds. (Incidentally, this is the attention span of the average zoomer.)
Here’s a few more insights to consider, in no particular order:
Start by writing the short video’s script before doing anything else. Use short sentences. Active voice. Simple vocabulary. You are speaking English potentially to people who struggle with English, or who are young, or tired, or distracted. But even your more sophisticated viewers will respond better to direct messages.
Here’s a good structure: Start with a hook (why should the viewer even look at your video and not skip?) This will be a joke, something interesting, a problem they may be facing, an engaging meme or video clip, a face, something. This must be done in the first 2 or 3 seconds of the video. Then, take a couple of seconds to introduce the name of the product. Then, in the body of your message, showcase the product, illustrating exactly three (3) main points about it. Three is a good number. Then repeat the name of the product. Repetition is key. Finally, close by showing the product again, (remember, repetition is key), and add your call to action. What do you want the customer to do? Go to your website? Download the app? Contact you? Where? Make it easy and direct. Add all the recognizing features of your product there. Branding (colors, fonts, tagline, icon, any graphics) should all be prominent in the last scene. If you are offering something for free, such as in a freemium business model, make sure to make FREE the last word, because that’s what people will remember.
There is going to be a voice talking. It’s better if it’s a female voice. Females sound attractive to your male audience, and appear less threatening to your female audience. Nobody wants to listen to a guy mansplaining your product.
Voice is not enough. Many people have their phone’s volume on mute. Subtitles must be available. Every. Single. Word. Is. Its. Own. Separate. Subtitle. Subtitles must be near the center of the screen, but maybe shifted slightly to the bottom or top so as to leave space for you to showcase the product. Text must be in a heavy sans-serif fond, with bright color, and with a thin dark border. You want the text to be readable on all kinds of background. If the platform supports it, also add the subtitles as text, even though you’ve hard-coded them into the video. I heard people like subtitles, so I add subtitles to my subtitles.
All platforms let you add some text to your video. Again, keep it short and to the point. Preferably the text should not deviate too much from the transcript of the video, which is your main message. Repeat your message there in the same template. Repetition is key.
You can use memes to make your message more engaging. Memes are not copyrighted, but are easily recognizable. Adding an element of humor to your ad can go much further than spending a big budget on a marketing campaign.
Graphics and animations are what make your video look professional. You can get graphics from stock image repositories. Be mindful of any copyrights.
There is theory behind colors. Blue and white conveys seriousness, etc. Same for fonts, design, etc. Know when to use serif versus sans serif fonts. You don’t have to be a graphics designer, but you should take some time to study the basics. Be aware of visual hierarchy. Learn these things, and you’ll never have to talk to a “creative” person again in your life. Big plus!
You should likely add some background music at low volume. The music should not overpower the speech or distract from your message. Viewers must subconsciously associate your product with positive, upbeat feelings. The music must be upbeat, and must strike a stark contrast to their otherwise miserable depressed life. The music must also be somewhat repetitive, so as not to distract from your messaging. Bonus points if it has a hypnotic element (ads work best by hypnotizing the logical faculties and appealing to emotion). The music must appeal to a wide array of musical tastes. Acoustic guitar riffs are the cornerstone of advertising. You can find royalty free music on pixabay. Be mindful of any usage rights. Sometimes the artist has submitted the music to a copyright ID platform, and you may have to request and submit usage rights. But things are simpler if you find music that is completely free to use.
Spam your ad to all the platforms that support video shorts
Video costs a lot of time and effort to make. At my current skill level, one video short takes about a day of work. But once you invest this cost, now your finished video can be thought of as capital that you own. You can show repeatedly, for little marginal cost, on all the platforms where people typically go to dump their garbage or to watch other people’s trash:
YouTube
Instagram
Pinterest
Tumblr
TikTok
Triller
Snapchat
Twitter
LinkedIn
Only losers pay for video editing
Before you go and pirate Adobe Premier from a torrent site, or pay some dude on Fiverr to make you a video, consider this: You can do it with open source software for zero cost, other than your time. And it’s a useful skill that you want to learn yourself, not delegate to some marketing-agency-dwelling type of creep. (Sorry, sorry, I promised I’m done with hating on marketing. I will be on my best behavior from now on.)
I was under the impression that OpenShot was somewhat limited and buggy. That’s because I used to install it via the Ubuntu repositories on my machine. For some reason, the repository has an ancient 2.x version of OpenShot which is very buggy. It crashes often, and produces nasty sound artifacts. This is not the case with the latest version of OpenShot. You should take a minute to add their official PPA and install the latest stable version from there.
Learning OpenShot is a breeze. It’s popular, so there are countless tutorials on Youtube. Focus on learning how to do animations by adding keyframes to your media. I will discuss here only two technical aspects that I found required a little bit of digging: How to create video shorts and how to add subtitles.
Shorts custom video profile
When you start a video project, you want to define the output video format. There are several templates available, but none corresponds directly to the specifications that we want for a video short. We are going to create a custom profile. Create the following file: ~/.openshot_qt/profiles/shorts with the following content:
Now you can start a new project with the “Short Vertical Video” profile.
Creating subs, the DIY way
There are, of course, a multitude of speech-to-text AI tools that will create subtitles for you automatically. One that works well is SubMagic. It offers many features including colors and emojis, and is well suited for social media videos.
But if your video is not too long, you can do it all by yourself. The advantage is that you don’t pay any money, and you are certain that there are no mistakes. You also have full control on where to break your sentences.
The best way to manually create subs is, surprisingly, not using a tool such as AegisSub, although it too can work well. I’ve found that the best tool for the job is Audacity. Here’s how you do it:
First, render the audio of your final video.
Load your audio in Audacity.
Go to Tracks → Add New → Label Track.
Select the first word. You can press Shift+Space to listen to your selection on repeat and ensure that you’ve selected the whole word and nothing more.
Press Ctrl+B to add a label.
In the box, type the word. In CAPITAL letters. This is for the TikTok generation. Don’t use punctuation unless absolutely necessary.
Deselect your selection, and select the next word. Audacity will help you by snapping the beginning of your selection to the end of the label you just entered.
Repeat steps 4 to 7 until you have done the entire length of the track. It gets easier as you learn how each phoneme looks like as a wave on the screen. For a 30 to 45 second video, it’s very doable.
Save your project as an .aup file, because you may want to go back to it and make changes, especially if you made a mistake.
Go to File → Export → Export labels. Save your labels to a text file. This file is not yet in a format that can be imported into OpenShot.
In SubRip, each entry starts off with a line that is the numerical index of the entry, then another line with the time range (two timestamps separated by -->), and finally one or more lines of text, followed by a blank line. OpenShot doesn’t like the line with the numerical index, so we remove it from our .srt file. You can replace the following regular expression that matches these lines, with the empty string: ^\d+$
Go to your video project in OpenShot. With a finished video, you will have several tracks full of small fragments of video clips, audio clips, and graphics being animated. You don’t want to attach your subs to any of that mess. Create a separate track for your subs.
In the new track, add a 1080×1920 PNG image that is completely transparent. Here’s one.
Stretch the image so it “appears” over the entire length of the video. (Of course, if your image is truly transparent, it won’t actually appear.)
Ensure that your cursor is positioned at the beginning of your track. (Use Ctrl+← to navigate to the beginning). If you don’t do this, when you later edit the Caption properties you will create a new keyframe, and you don’t want that. You want the properties that you’re about to enter to apply to the entire track.
Go to the Effects tab, and drag the Caption effect onto the transparent image in your subtitles track.
The letter C will appear on the track. Click on it to edit the properties of the Captions effect.
I will share here the settings that I like to use in my videos. You can experiment with other settings of course. Font: Arial Black Bold 100pt (or any heavy font). Font size: 65. Font alpha: 255. Font color: Yellow #FFFF00. Stroke width: 3. Border: black #000000. Left size: 0. Right size: 0. Top size: 0.75.
Now go to the right side of the screen, and paste the SubRip subs (with the index lines removed).
Watch the video to ensure that all the subs are shown. If a line is too wide, it will not be shown. So check the lines with the most text. If a line is not shown, either break it into two, or reduce the font size. Your lines should be individual words, so they should not be too long.
That’s it. You can now render your ad and spam-post it on all the aforementioned platforms. Add it into your articles, above the fold. Then, post links to your video shorts again and again. Repetition is key.
In this article I’m going to talk about how I set up two WordPress sites on one server. None of the articles I could come up with covered all the topics I was interested in. Not exactly groundbreaking, in fact it sounds simple. But the devil is in the details. To actually perform such a setup for the first time is actually pretty daunting. From setting up the DNS records to getting file permissions to work, to getting the reverse proxy right, it’s all a complicated mess that I’m going to delineate for you (and me) here, while it’s still fresh in my head.
Features
Two WordPress sites: https://www.example1.com and https://www.example2.com.
Redirects from https://example1.com, http://example1.com, http://www.example1.com to https://example1.com (and the same for example2.com).
The containers must run as a service, so that they start with system start, and exit gracefully on system shutdown.
Daily backups of all WordPress files and MySQL databases.
Networks of the two sites should be isolated for security.
Shameless plug of my referral links
We start with a hosted server. This can be a dedicated server or a server slice. Hosting providers that I like are:
DigitalOcean – Using this link you get a $200, 60-day credit to try their products. If you spend $25 after your credit expires, I will get $25 in credit.
Hostinger – You don’t get anything with this link, except for a great hosting service. Again, I get a commission from this link if you stick with Hostinger for 45 days. Think of it as my reward for writing such a great article for you.
I have a Debian droplet on DigitalOcean with 2GB of RAM, but with some tweaking it’s possible to squeeze two low-traffic WordPress sites in 1GB, if you really need to keep the monthly costs down.
First let’s get the (DNS) record straight
The first order of business is to setup the DNS records. We’re going to need two A records to point to our server’s IP, and two CNAME records that will be wwww. aliases of the bare domain. Oh, and we’ll need some NS records to point to the domain name provider (in this case Digital Ocean).
Type
Hostname
Value
TTL
A
example1.com
(my server’s IP)
1800
A
example2.com
(my server’s IP)
1800
CNAME
www.example1.com
alias of example1.com.
1800
CNAME
www.example2.com
alias of example2.com.
1800
NS
example1.com
ns1.digitalocean.com
14400
NS
example1.com
ns2.digitalocean.com
14400
NS
example1.com
ns3.digitalocean.com
14400
NS
example2.com
ns1.digitalocean.com
14400
NS
example2.com
ns2.digitalocean.com
14400
NS
example2.com
ns3.digitalocean.com
14400
I like to keep the TTL (Time-To-Live) values low until I’m finished with my setup. I’ve set everything to 1800 seconds which is half an hour. Once I’m sure that everything is OK, I can increase the values to something larger like 14400 (four hours).
ssh
We are going to need to be able to login to the server with a passwordless setup.
Login as root to the new server via the admin console.
Create a regular user with adduser:
adduser yourusername
Then add the user to sudoers with:
usermod -aG sudo yourusername
(Replace yourusername with your username.)
Once we are on our local machine, we check if we already have an ssh key with:
Once we are sure that there is a key, we upload it to the new server with:
ssh-copy-id yourusername@server_ip_address
(Again replace yourusername with your remote username, and server_ip_address with your ip address. You will need to enter the password you entered in adduser.)
Docker compose
First, let’s install docker on the server by following the installation instructions for Debian. I am not going to repeat the instructions here. If you have chosen a different distro, follow the respective instructions.
We are going to create a docker-compose.yml file. This file describes how the different docker containers are orchestrated.
We are going to need four containers:
Two databases for the two sites.
Two WordPress installations.
I’m first going to show some simple compose configs with the basics, then we are going to add the bells and whistles. Here goes:
We are defining our composition to have a name. Here I am using droplet. This will also be the prefix for the names of all the containers.
We are defining two networks, net1 and net2. Only containers on the same network can talk to each other. We don’t want our example1.com WordPress to have any access to the MySQL database of example2.com.
Next we are defining two identical mysql:8.2.0 containers, named db1 and db2.
Each of the two databases is put in its respective network (net1 and net2).
We want a database that has crashed to restart, unless we explicitly stop it.
We are going to let the databases listen to TCP port 3306. This is the port where WordPress will connect. All other ports are firewalled.
We are going to mount the /var/lib/mysql directories into docker volumes named db1volume and db2volume.
Next we are going to use some environment variables that the startup script inside the mysql image recognizes. These will set up a root password, a new empty database, and a username/password pair that WordPress will use to access this new database. The startup script will do all the CREATE DATABASE, CREATE USER and GRANT magic for us. You can learn more about the MySQL docker image here.
A tale of two WordPresses
Next, let’s also add the two WordPress services (these also go under the services section along with the databases):
We have named the two WordPress containers wp1 and wp2 and assigned them to our two networks, net1 and net2.
We have defined that these depend on their respective databases to function.
We have defined that these containers are to be restarted if they crash, but not if we explicitly stop them.
We are exposing only HTTP port 80 to the networks. All other ports are firewalled. We are not exposing port 443 here. TLS encryption will be done at the host level that will run the reverse proxy (see below).
We are mounting two local directories here ./wp1fs and ./wp2fs. These will contain the WordPress installations. The first time that the containers run, WordPress will be installed in them. A special wp-config.php file will be placed in there. This file pulls the DB connection settings from the environment variables that we specify below.
We are port-mapping the HTTP 80 ports to the host’s ports 8101 and 8102. These are the ports that the reverse proxy will use. They are bound to the loopback network (127.0.0.1), and are therefore not exposed to the outside world. If we had used just 8101:80, this would map port 80 of the container to port 8101 of the host on all network interfaces, including the one facing the outside world. This is not ideal. We only want access to our services through our reverse proxy.
The WORDPRESS_* environment variables are specific to this wordpress image. We specify the databases, the login credentials that we also specified above, and we turn on debug logging. To learn more about these environment variables, click here.
NOTE: I have made the decision here to put the databases into system volumes (these live usually in /var/lib/docker/volumes and can be shared between containers, the WordPress filesystems are mounted in local directories which I call wp1volume and wp2volume. If you prefer to have all volumes unde /var/lib, you can delete the ./ prefix in front of the volume names.
The bells and whistles
If you thought that’s enough, you are gravely mistaken. Here’s a few more things to take care of:
Database collation
We are going to set the databases a UTF-8 multibyte collation for unicode support. Under the environment variables in the database services, we are going to add an explicit mysqld command:
And under the WordPress services, we are going to add the following environment variable:
WORDPRESS_DB_COLLATE: utf8mb4_unicode_ci
File permissions
If we run the above containers, WordPress won’t be able to install or remove any themes or plugins, and it won’t be able to do anything that requires writing to the file system.
This is because, in the WordPress images, the user that runs apache has a different uid and guid than the file system. The files are owned by uid1000 and guid1000. We can specify that the user running stuff inside the container has the same numeric ids. To do this, we add the following to the two WordPress services:
user: 1000:1000
Database memory
By default, a mysql instance will take up at least 360MB of memory once it’s running. Most of it is because of the Performance Schema instruments, which take up a lot of memory.
The Performance Schema is a database that keeps track of the mysqld server’s performance, and is useful for diagnostics. If you are not going to use this feature, then you can turn it off. The memory usage of each DB container will then fall to a little over 100MB.
We are going to create a file named disable-perf-schema.cnf with the following contents:
[mysqld]
performance_schema = OFF
This will be added to the mysql server’s config files. The server includes any .cnf files in the /etc/mysql/conf.d directory into its configuration. We can use the volumes section to map this file into our two db containers:
There are more hacks to reduce the memory usage of mysqld, but these are beyond the scope of this article. For example, you can look into reducing the InnoDB buffer pool size.
Log rotate
We have enabled debug logging, because reasons. This is cool, but the /var/www/html/wp-content/debug.log files will eventually fill up our containers if left unchecked. Enter logrotate to the rescue:
We are going to create a file named wordpress.logrotate with the following content:
This will gzip old logs daily and will delete even older logs. If you are not sure about the details, ChatGPT and Bard can explain exactly what each line does.
Note how we use again the uid and guid of the WordPress image.
Let’s mount this file into our WordPress containers, by adding a line to their volume clause:
We can start this with docker compose up (we must first cd into the same directory as the .yml file).
We can see if it’s running with docker compose ls, and we can see the containers with docker container ls.
We can inspect memory usage with docker stats.
We can stop the containers with docker compose down.
If we also want to wipe the database volumes and start over, we can do docker compose down -v (DESTRUCTIVE!!!).
We can go into the shell of the first database with:
docker exec -it droplet-db1-1 bash
And then, we can go into the mysql console with
mysql -u root -pwp1_root_pass
We can go into the shell of the first WordPress with:
docker exec -it droplet-wp1-1 bash
If we need to, we can install wp-cli using instructions from https://wp-cli.org/. The copy of wp-cli will not be persisted into the container across restarts. (Note: it’s possible to add special containers with wp-cli pre-installed, but again this is out of scope of this article. For more information, see the CLI images here.
DaaS (Docker-as-a-Service)
We don’t want to have to issue docker compose up every time the server starts, and docker compose down every time the server stops. Let’s create a systemd unit, so that it runs as a service.
We’ll create a file named /etc/systemd/system/docker-compose.service with the following carefully crafted contents:
Replace the description with something less silly (optional).
Note how we only start this service after the docker service starts.
Note that we do a --detach. This will start the containers in the background and exit, without showing the logs of all the containers in the standard output.
We can now start the service with
sudo service docker-compose up
And stop it with
sudo service docker-compose down
If we want to see the logs of all the containers, we can type
docker compose logs -f
We should now be able to do curl http://127.0.0.1:8101 and see the HTML of the front page of the first WordPress.
The reverse proxy
The database and WordPress containers are running, but they are not yet exposed to the outside world. To do this, we are going to use nginx as a reverse proxy.
The reverse proxy will:
handle all the redirects that we need
expose the apache2 servers to the outside world
handle the TLS encryption
First we setup Let’s Encrypt. How to do this is beyond the scope of this article. You can look here for a good introduction.
The bottom line is that certbot must be installed, and the following public and private certificate files must exist on your server (host):
We can test our syntax to see that it is correct with:
sudo nginx -t
And finally we can restart the nginx server with:
sudo service nginx restart
We can check the status of the server with:
sudo service nginx status
If everything is working correctly, and if the DNS records have had time to propagate, then we can visit our sites and run the famous WordPress installation process:
https://www.example1.com/
https://www.example2.com/
Emails
If only the above was enough. Sadly, our WordPress installations need a way to send emails, otherwise the webmaster experience is going to suck big time.
I say sadly, because setting up sendmail first on the host is relatively easy, but then setting up SMTP proxies in the WordPress containers is not something I am familiar with. Sorry guys, in the interest of keeping things simple, I’m going to cheat a little here. Here’s what I did:
Install the free WP Mail SMTP plugin on both sites.
Create an application-specific password in my google account.
In the WordPress admin screens, go to: WP Mail SMTP → Mailer → Other SMTP.
Enter the following settings:
SMTP Host: smtp.gmail.com
Encryption: SSL
SMTP Port: 465
Auto TLS: ON
Authentication: ON
SMTP Username: (my gmail address)
SMTP Password: (the application specific password that I just created).
Hit Save Settings.
Go to WP Mail SMTP → Tools and send a test email.
If everything works, then WordPress and its plugins can now send emails. But it will only be able to send email into spam folders, until we add a Sender Policy Framework (SPF) record to our DNS entries:
Type
Hostname
Value
TTL
TXT
example1.com
v=spf1 a mx ~all
1800
TXT
example2.com
v=spf1 a mx ~all
1800
Disclaimer: These DNS records are actually not related to sunscreen in any way.
The above TXT records tell recipients to treat all emails coming from servers pointed to by the A or MX record of your domains as safe, and others as potentially suspicious. Again, use your favorite AI chatbot to constuct an SPF record that matches your needs.
Nothing more permanent than a 301 redirect
If all works, it’s now time to turn the soft redirects into permanent (hard) redirects. Edit the reverse proxy config and change any 302 redirects to 301. Any browsers visiting your site will cache these redirects for eternity.
It’s also now a good time to increase the Time-to-Live of all the DNS records to something like 4 hours, or 14400 seconds.
Backups
You would think that by now you’re finished, but you’d be wrong!
First, turn off the server or droplet and take a full backup, snapshot, or whatever. Future you will thank you.
Then, let’s see how we can take automated daily backups. We can either pay the hosting provider every month to do this for us, or we can spend a few minutes to set up a few cron jobs. Let’s be cheap and do it manually.
I have a raspberry Pi at home that is always on. It does various things like take backups, ping various services and email me if they are down, trigger wp-cron URLs, control crypto miners, run services I need such as my ticket system, and in general runs any other odd 24/7 task. You should also have one such low-power system. The great thing with Raspberry Pi is that it’s easy to take out the MicroSD and gzip it into a mechanical disk, so the backup mechanism itself is nicely backed up in its entirety. (Yo dawg, heard you like backups…)
We’ll now use our local always-on Linux system to take daily backups of our online filesystems and databases:
Local backups.sh script
First, let’s create a DB user that only has enough access to take backups from both databases, but no more:
Login to the MySQL consoles of each database and create a wp_bu user that will do backups:
CREATE USER 'wp_bu'@'localhost' IDENTIFIED BY 'SOMESTRONGPASSWORD';
GRANT SELECT, LOCK TABLES ON wp_db1.* TO 'wp_bu'@'localhost';
CREATE USER 'wp_bu'@'localhost' IDENTIFIED BY 'SOMESTRONGPASSWORD';
GRANT SELECT, LOCK TABLES ON wp_db2.* TO 'wp_bu'@'localhost';
We only need SELECT, but since we want to call mysqldump with the --single-transaction argument, we’ll also need to grant the LOCK TABLES permission. No point in having an ACID database if we’re going to take backups of an inconsistent state now, is there?
We’ll now create a bash shell script that does our daily backups. Let’s place it in our local backup server and call it backups.sh:
#!/bin/bash
# ensure dirs exist
mkdir -p /path-to-backups/cache/wp{1,2}volume /path-to-backups/server
# download DBs to SQL files
ssh -t server "docker exec droplet-wpdb-1 nice -n 19 mysqldump -u wp_bu -pSOMESTRONGPASSWORD --no-tablespaces --single-transaction wp_db1 | nice -n 19 gzip -9 -f" >/path-to-backups/server/wp_db1-`date --rfc-3339=date`.sql.gz
ssh -t server "docker exec droplet-wpdb-2 nice -n 19 mysqldump -u wp_bu -pSOMESTRONGPASSWORD --no-tablespaces --single-transaction wp_db2 | nice -n 19 gzip -9 -f" >/path-to-backups/server/wp_db2-`date --rfc-3339=date`.sql.gz
# download wp-content files to backup cache
rsync -aq server:~/wp1fs/* /path-to-backups/cache/wp1volume
rsync -aq server:~/wp2fs/* /path-to-backups/cache/wp2volume
# Zip downloaded wp-content files
zip -r9q /path-to-backups/server/wp1-`date --rfc-3339=date`.zip /path-to-backups/cache/wp1volume -x "**/GeoLite2*" -x "**/GeoIPv6.dat"
zip -r9q /path-to-backups/server/wp2-`date --rfc-3339=date`.zip /path-to-backups/cache/wp2volume -x "**/GeoLite2*" -x "**/GeoIPv6.dat"
# prune old DB and FILE backups from local backups
cd /path-to-backups/server && ls -1tr | head -n -30 | xargs -d '\n' rm -rf -
Again, a lot goes on here. Let’s unpack:
The script creates directories server and cache under /path-to-backups. Replace this path with something that points to the directory where you want to keep your backups.
We then ssh to the host using the -t argument because we are in a headless environment (cron). We issue a docker exec command into our databases. Notice how we do not use the -it arguments to docker exec, since this is a headless command (no TTY attached). The command is a mysqldump command that uses the credentials we just created to export the databases in a single transaction each. The SQL output is compressed with maximum compression (-9) and the binary output of gzip is forced (-f) into the standard output, which is then sent over the ssh connection. In our local backups server, we redirect this compressed stream into an .sql.gz file. The file name starts with wp_db1- and includes the current date in YYYY-MM-DD notation. (RFC 3339 is my idea of a perfect date, btw). The --no-tablespaces argument is need in MySQL 8.0.21 and later, otherwise you’ll need the PROCESS global permission. (Unless you are using tablespaces you don’t need it, hence the argument --no-tablespaces.) Notice that we make sure to be nice to other running processes because we don’t want to impact the performance of the web server with our backups. 19 is the idle CPU priority.
We then use rsync with the quiet (-q) and archive (-a) flags to copy the files of our WordPress installations into our cache/wp1volume and cache/wp2volume directories. The advantage of using rsync is that only changes to these directories will be transferred.
We then create a zip file for each of these directories. We name the zip files with the prefixes wp1- and wp2- followed again by our idea of a perfect date. Many WordPress plugins include a database of IPs mapped to geographical locations. These files are large and can be found online. If we don’t want to save these, we can exclude them (-x flag), but this is optional.
Finally we list the files we created (both .sql.gz and .zip files) and we only keep the last 30, deleting any older ones. Since we have two files for each of two databases, this will retain daily backups for the last week or so.
Make the script executable with
chmod +x backups.sh
We run the script once, and we check the .sql.gz files using zless and the zip files with unzip -l.
Once we are certain that all data is backed up by the script, we add it to the crontab. Edit the crontab with crontab -e and add the line:
This will execute the backups every day at 4:20 in the morning.
Checking the backups
The server works and is fully backed up. You would think that you’re done by now. That’s where you’d be wrong again!
Having backups and not checking them regularly is worse than not having backups at all: You are being lulled into a false sense of security. You may act precariously, thinking that you can always go back to the last backup. However, all backup mechanisms can fail, for any number of reasons.
What I do, is I’ve set up a weekly reminder in my Google calendar to check the backups. It only takes half a minute per week to ssh into my backup server and do an ls -l, thus ensuring that the latest backups exist, and their file size is what I’d expect. I keep old backups for about a week, hence the weekly reminder.
I also have another reminder every three months, to backup the MicroSD of my Raspberry Pi backup server. Once every three months, I shutdown the Pi, take out the MicroSD, put it into my work PC, and copy the entire image into a file, stored on my mechanical disk:
My config is actually a little bit more complex than the one discussed above. To save some more server memory, I had to put both databases into the same MySQL container, and set up two different DB users with access restricted to each respective database. But you shouldn’t do this at home, because isolation!
This article is being served by the containers I discussed here, and will be backed up early tomorrow morning, via the mechanism I shared with you above. Which is pretty meta, if you think about it!
I never expected to compose such a long, self-contained article on containers and docker compose. But now it’s finished and I can hardly contain my excitement!
Like any self-respecting server-side app, WordPress also features logging. While this is usually discouraged, themes and plugins can write to this log with error_log. Any PHP warnings or errors will also be dumped to the logs. That is, if logging is enabled.
How to enable logging: RTFM
To enable logging, edit the wp-config.php file.
First, add define( 'WP_DEBUG', true );. This will enable “debug” logging, as explained in the article Debugging in WordPress.
Then, add define( 'WP_DEBUG_LOG', true ); to make the log be written to a file, /wp-content/debug.log.
Finally, you don’t want any PHP warnings or errors to spill over into your site’s markup and cause problems. Add define( 'WP_DEBUG_DISPLAY', false ); and @ini_set( 'display_errors', 0 ); for good measure.
Great! Now you’re good to go. Debug logging has been enabled.
“Debug” logging?
But I take some issue with that. Why is logging labelled “debug” logging? Are there no other legitimate reasons to keep logs? WordPress documentation doesn’t think so:
It is not recommended to use WP_DEBUG or the other debug tools on live sites; they are meant for local testing and staging installs.
Perhaps this is OK for most people. WordPress is meant to be used by non-programmers, and generally by people who wouldn’t know what to do with a log file. But if you can jam with the console cowboys in cyberspace, I think you should keep logging on, even in production. Here’s why:
Health status
The WordPress ecosystem is a beautiful mess. Typically you will run all kinds of plugins of varying quality. I know that I am responsible for dumping some low-effort buggy code on to the WordPress.org repository, and, believe me, I am not the only one. When you put many pieces of software together in the same system, things can break. Yes, you have the PHP error logs which capture most errors, but it’s helpful to have a record of the errors and any error_log output. If you have live logs, you can address incidents faster. In my mind it’s a no-brainer.
Security
In case of someone breaking in to your site, and yes, this happens a lot, it may be possible to figure out what happened by looking at the logs. You may be able to figure out which plugin the hacker exploited and in what way, by looking at the failed attempts that preceded the successful break-in.
For extra credit, set up a cron job that stores backups off-site to another server. Evenif a hacker manages to clear the logs, you still have data for your forensics investigation.
Disk space
The main arguments against logging are that
writing logs degrades performance, and
writing logs can fill up disk space
Argument #1 is not even worth discussing in the year of our Lord 2023, when SSDs are the norm on server hardware. I can guarantee you that even if you care about performance a lot, the milliseconds wasted on logging are the least of your concerns. I’d much rather have logs available when I need them, if this is going to save me time and money by avoiding or fixing incidents.
Argument #2 is perhaps less laughable, but still invalid. The disk space argument is only brought up by people who haven’t heard of logrotate.
Let me show you my /etc/logrotate.d/wordpress file on this blog’s server:
So, full logs for the last 24 days are taking up 272 kilobytes when compressed. Disk space well spent, if you ask me.
wp-console plugin
Even a console cowboy will agree that sometimes it’s more convenient to view the logs via the WordPress admin. For these rare occasions, I use wp-console. Next to the Console tab, which is very useful by itself, there is the Debug Log tab.
Make a habbit out of it
Let’s take a step back: WordPress is usually the main engine of a small business. Running a business means executing a set of processes repeatedly, with the hope that these processes will create value.
I like to be proactive: One of the processes that I execute repeatedly as part of my business, is to visit the site logs every 3 months. I have a calendar reminder for this, pointing to a ticket that’s all about inspecting logs. As I identify problems that I want to fix, I open separate tickets for those as well.
Logs are compressed
First, I look at the logs. Today’s file is uncompressed (debug.log), while older files are gzipped (debug.*.log.gz). Instead of ungzipping the files, I usually like to inspect them in place via an ssh shell, using the zTools:
use zcat instead of cat
use zless instead of less
use zgrep instead of grep
use zfgrep instead of fgrep
use zegrep instead of egrep
How I inspect logs
Usually, when you look at such logs, you will see one single type of warning or notice being repeated a lot, possibly because of a plugin or theme.
Let’s say you see a “PHP Notice: Undefined variable: foo” line a lot, coming from some plugin. It’s not causing any real problems, but it gets written out with every HTTP request. You are not responsible for maintaining this plugin, but this line is obscuring your view of the logs. So, just look at the logs without it:
Now you will see a listing of all your logs, except for that notice. The next most common notice will become apparent. Let’s say that this is a “PHP Notice: Undefined index: bar” in another plugin, that you are also not the maintainer of. You can filter for that as well. Just daisy-chain your greps using pipes:
You could go into the source code of these files and add a @ character in front that line, to suppress the warnings, at least until the plugin in question is updated by the developer. But I don’t recommend it. Too much effort for too little gain. gzip does an excellent job of compressing similar strings repeated thousands of times. This is literally what huffman trees were built for.
Rinse and repeat
Continue chaining greps, until you get to an error that you care about. Maybe it’s an error that looks ugly, worries you, or just feels bad. Maybe an include is missing. Maybe you can investigate, or even fix the issue. Or maybe you feel like you have to notify the developer via the plugin’s support forum. Maybe you’ll decide that a plugin causes too many errors and is easily replaceable by another similar one.
Deprecated code
Depending on what you are doing, you may want to hide deprecation notices. At the time of this writing, even the latest version of WordPress core writes a lot of deprecation notices if you are running PHP 8. If you’re not a core developer, it’s not our job to fix them, so filter them out with: | grep -v 'PHP Deprecated.*/var/www/wordpress/wp-(includes|admin)'. See what I did there? I filtered out only Deprecation warning lines coming from the wp-includes or wp-admin directories, but not Deprecation warnings from other components (plugins or themes). Regular expressions are your friend.
Code that is deprecated in PHP8 will stop running in PHP9 when it arrives sometime this year. Before you upgrade your PHP, you may want to know which plugins are going to have problems. A plugin developer who is proactive will be fixing these.
It’s always better to be proactive with these things. Also, be mindful of the quality of the code you are running on your servers. A plugin that dumps too many warnings into the server logs (or into the browser’s console log, for that matter), is a low-quality plugin.
Conclusion (and shameless ref link plug)
If you are proactive in that way, you will catch incidents before they occur.
Of course, you can only do this if you are running your WordPress on a server with shell access. Managed hosting is good for most people, but if you are the hands-on type of person, you will want to have shell access. With ssh access you can harden your server’s security yourself, and then noone can ruin your server for you. Be an grown-up, ruin it yourself!
This blog runs on a DigitalOcean droplet. I honestly cannot recommend them enough. I am happy because my droplet is always available, with great up-time, great documentation, great admin screens, never even needed to contact support. They have a good choice of data centers around the world, an API for spinning up new instances programmatically, and if there is ever any downtime or even a network slowdown, they let you know way in advance. Taking snapshots of your droplet is a breeze. Some of the lowest prices I’ve seen, starting from $4 per month for a low traffic site. If you don’t feel like setting up everything up by yourself, they also have a WordPress-WooCommerce Droplet in their marketplace.
If you sign up with this referral link you get $200 of credit which you can spend over the first 60 days. And yes, if you spend $25 or more with them, I get $25 for my trouble too, so thank you for that!
Large Language Models (LLMs) are nothing new, with GPT-3 having been around since 2016. However, access to such systems was limited to a few researchers until recently. Now that ChatGPT is upon us, everyone has to adjust: Google is finally incentivized to enter the race. This was not in their best interest up to now, but Generalized Pretrained Transformers have already done what many thought impossible: They made some people use Bing search!
But jokes aside, and while we wait for Bard, Google recently announced that their search algorithm will penalize articles that seem to be AI-generated (i.e. that lack in human-like originality). At the same time, companies like GPTZero are springing up like mushrooms left and right, offering AI-generated content detection services. Their detection tools have varying rates of success.
As with all new technologies, it’s helpful to revisit xkcd 1289: Simple Answers. TL;DR There’s no need for alarm, this new thing is here to stay, it’s not the end of the world, some people will lose their jobs, and ultimately we’ll all have to adapt and learn to live with it. And yes, it will be used for sex. There’s already AI girlfriend apps being built around the API.
Anyhow. Let’s figure out how to use this to our advantage: Articles already abound on how to ask the right questions, or “prompts”, for every industry. This is yet another one of these articles!
While anyone can interact with ChatGPT using natural language, you’ll get better results if you ask the right questions, and in the right way. An authoritative resource that is not too technical is this cookbook from OpenAI. In short, it’s best to not ask the model to do all the work for you. Instead, try to break up your work into small steps, and ask each step in sequence. This improves precision of responses and reduces hallucination. Go ahead and read the cookbook, it’s the operator’s manual for a tool that has proved its usefulness in all walks of life.
As a WordPress plugin developer, I have found ChatGPT immensely useful in all stages of software development. When trained with the (text-davinci-003) model, it performs exceptionally well with computer source code, bridging the gap between natural and formal languages in a way that can speed up your dev work.
It so happens that I hold the -somewhat controversial, and arguably simplistic- view, that all software development methodologies are basically Waterfall with extra steps. Love it or hate it, Waterfall is what all methodologies originate from, and ultimately deviate from. What I mean is that, whichever methodology you follow, you will not avoid doing the stages that comprise Waterfall. All that changes is the order in which you visit these stages.
I’m just going to leave this here.
In any case, I recently found myself thinking about the stages of Requirements capture, Analysis, Design, Implementation, Testing, and Devops (Deployment, Maintenance, Monitoring), as areas where ChatGPT can improve my workflow. It’s efficacy on some of these stages is more obvious than on others.
Let’s visit each one in sequence.
Analysis, requirements capture
This is where I think ChatGPT really shines. It can help you to brainstorm for new ideas, and explore feasibility of these ideas. It will also help you identify likely features for an idea. Just be aware of the hallucination problem. Don’t ask it what software exists in a particular niche. Instead, ask it for ideas, or intersections of ideas. Here’s some questions that you might ask:
List some ideas for developing useful SAAS applications that can be monetized.
List 10 ideas for developing WordPress plugins that involve retrieving and presenting data from open APIs.
What open APIs or databases are there for retrieving information on spare car parts?
How can I monetize a WordPress plugin?
You have to approach the responses critically, but it really is a great way to brainstorm and come up with new ideas.
Once you settle on an idea, you can also use it to brainstorm on a list of possible features. Go ahead and ask it:
What features would a WordPress plugin have for placing posts on a map?
It gave me a good list of features. Go ahead and try it out.
Design
This is the part where the human will still be needed I think, at least for the time being. As software engineers, the most creative part of our job is to match a set of requirements to a particular design. Nevertheless, ChatGPT can help us in this area as well. Try asking it a specific question like:
How would I go about creating a WordPress plugin that shows code quality scores next to each active plugin? I would like it to evaluate code quality based on existing static analysis tools like phan, PHPStan, CodeSniffer, etc.
The answer will surprise you. It will break down the project into more manageable tasks. In summary, I got the following tasks:
Choose a static analysis tool
Create a WordPress plugin
Integrate the static analysis tool
Display the scores
Add customization options
Test and refine.
You can now go ahead and open dev tickets for each of these tasks. You can also ask it to generate code for each step. The boilerplate code that you get will not be complete, but it will get you half way there.
Which brings us to implementation:
Implementation
Besides analysis, this is the other stage where ChatGPT is a real time saver. Say for example that you want to create a new Custom Post Type. You could look at the documentation, or search the web for a blog post with a concrete example. WPBeginner has an example on how to create a Movie post type, and you can adapt it to whatever you are building. But wouldn’t it be awesome if you could somehow get the exact code that you need? Try asking this:
Show me how to register a CPT in WordPress for coins, with meta values that are of interest to collectors.
This gave me not only the code to register a Coin post type, but also code for metaboxes with HTML forms that let you edit the following fields: Year, Country, Mint, Condition. All of these are fields that are actually of use to collectors. Not a bad place to start. You can add more fields if you like. Don’t like the code style it uses? You can even ask it to change the code it generated. e.g.
Please rewrite this code using callbacks.
It will do it! You can shape the code using natural language conversation. Once it’s close to what you want, paste it into your IDE, and take it from there!
It’s also good for generating PHPDocumentor comments. Just ask it to generate phpdoc for the following code, then paste your code. The result will make sense, even if it requires some editing on your part.
Try asking this:
Show me how to display an admin notice in WordPress so that it can be dismissed permanently by the user.
It will actually show you how to hook into admin_notices and also generate the JavaScript code that is required to do an AJAX call and update some user meta value.
Say you are looking at the docs for an API, and examples are given in curl, but you are implementing PHP code that consumes this API. Here’s something you might ask:
Please translate the following curl command to PHP: curl -X POST https://example.com/api/endpoint -d ‘param1=value1¶m2=value2’
All of this you could do by yourself, but ChatGPT is so much faster.
Testing
It’s a well known fact that the model can generate unit tests. Give it a function and ask it to generate PHPUnit tests. It will do it, and do it well.
Deployment and Maintenance
ChatGPT is well-versed in shell magic. Ask it in plain text to generate a cron entry, or a System V unit file, or a bitcoin core wallet config file, or a docker file, a complex SQL query, or anything really.
For example, you may ask:
Write a linux shell command that will show me the processes that are currently writing the most to disk.
It will reply with a few paragraphs on how to install iotop and how to use it, along with more helpful info.
Another more complex example:
Write me a cron command on linux that will email me if the root partition has less than 1GB free, but will not email me more often than once every 24 hours.
The result is impressive. Not only did it come up with:
but it gave a very helpful textual explanation of how this works:
This command checks the available space on the root partition using the df command and awk to get the available space, which is then compared to the value of 1048576 (which is the number of kilobytes in 1GB). If the available space is less than 1GB, an email alert will be sent to the specified email address using the mail command.
To ensure that the email notification is sent only once every 24 hours, the command uses the find command to look for a file named “root_partition_alert” in the /var/log directory that has been modified in the last 24 hours. If such a file exists, the false command is executed, which does nothing but exit with a non-zero status code. If the file does not exist or is older than 24 hours, the email notification is sent, and the touch command is used to create a new file named “root_partition_alert” in the /var/log directory with the current timestamp, which will be used as a reference for the next run of the command.
Note: Replace your_email_address@example.com with your actual email address.
Holy cow! Did I just give it requirements in English, and it came back with code that satisfies my requirements? In truth, I haven’t tested the command, but even if it’s not 100% correct, it’s a very good place to start, considering that the answer comes up immediately. You can study its reasoning, get ideas, and improve on it.
Your new pal can also help you with your containerization needs:
Show me a dockerfile that will run a node server with an express application.
The code it came up with was:
# Use an official Node.js runtime as a parent image
FROM node:14
# Set the working directory to /app
WORKDIR /app
# Copy package.json and package-lock.json to the container
COPY package*.json ./
# Install app dependencies
RUN npm install
# Copy the rest of the application code to the container
COPY . .
# Expose port 3000 to the host machine
EXPOSE 3000
# Start the Node.js server with the express app
CMD [ "npm", "start" ]
And again, this all came along with a helpful explanation of what the code does. Super useful.
Fun
We’ve seen how ChatGPT is the perfect tool to help a WordPress plugin developer.
Lately I have been using it for more than just work. I recently downloaded a movie that had a wrong aspect ratio. I found out that, in VLC, when I switch to 16:9, it looks correct. However, I wanted to show the movie on a projector where I’m not sure if it has an aspect ratio correction feature. Thankfully, ChatGPT told me that I can do the following:
ffmpeg -i movie.mp4 -aspect 16:9 movie.mp4
Much faster than looking up the documentation, and at least as fast as looking for the answer online, but without the extra hassle of having to read people’s opinions on the matter, and I didn’t need adblock to avoid looking at ads. I just got the answer I was looking for, in text form, ready to copy to the shell, and it worked.
Giving a title to this article
I asked the question:
I am writing an article on how ChatGPT can help WordPress plugin developers with their work. Can you please suggest a few witty or catchy or memorable titles for the article?
The reply was:
Sure, here are a few suggestions for your article title:
“Revolutionize Your WordPress Plugin Development with ChatGPT”
“The Ultimate Tool for WordPress Plugin Developers: ChatGPT”
“From Idea to Execution: How ChatGPT Can Streamline Your Plugin Development Process”
“ChatGPT: The Brain You Need for Your Next WordPress Plugin”
“Get Your Creative Juices Flowing with ChatGPT: The AI Assistant for WordPress Plugin Developers”
“Simplify Your Plugin Development with ChatGPT: The AI-Powered Assistant for WordPress Developers”
“Unleash Your Potential as a WordPress Plugin Developer with ChatGPT”
“ChatGPT: The Secret Weapon for Successful WordPress Plugin Development”
“Master the Art of WordPress Plugin Development with ChatGPT by Your Side”
“ChatGPT: The AI-Powered WordPress Plugin Development Assistant You Can’t Do Without”
As you can see, I decided to combine the first and third ideas for this article.
My personal thoughts on all this
I remember when Google search was a new thing and it took all of us several years to learn all the things that could be found with it. In the beginning, there were many things that I wasn’t searching on google, because it hadn’t yet occurred to me that the answer could be found there. This was the early days of the web. As years passed, we all learned that we can look up medical information, where to purchase products, find maps and travel info, music and lyrics, etc. We also learned not to believe everything we read, just because it’s posted on a website somewhere. We learned to believe official websites more than reddit posts or tweets, and we learned to navigate around, and through, the more shady parts of the web. Similarly, it will take a while before we learn all the useful ways in which ChatGPT can help us, and also what to watch out for.
The success of ChatGPT also reminds me of the evolution of academic research on NLP, and translation in particular. For years people were battling the problem using various language representations, such as syntax trees and clever algorithms. Turns out, the breakthrough that gave us cheap and fast natural language translation was SYSTRAN: Nothing more than a big dictionary of words and phrases, with some dumb statistical stuff added in. Just translate every word to the target language. Did your system get a phrase wrong? Great, just add the correct translation to the dictionary. The secret was not in the algorithm, but in the big data.
ChatGPT is arguably just some artificial neural nets, and these have been with us since the 60s. But now we have GPUs and big data. People have been typing their thoughts on the web for decades now. No wonder that a breakthrough in AI, one that’s so significant as to touch people outside the field, occurred now, and not earlier.
So, I have been thinking lately: What if the thing we call “symbolic intelligence” is just language transformation? When we use language to reason, it’s likely that what we do in our heads is not very different from what these LLMs do. Symbolic reasoning is not the only type of thinking we humans do, but arguably it’s the most important type of thinking that we do in our day jobs. And language transformers can help a lot in this.
As someone with autism, I can deeply relate to ChatGPT: It’s not particularly smart, but it is well-read, and patient. It does not judge, but tries to be helpful at all times. And it prefers to communicate via chat rather than face-to-face!
Ultimately, the fact that it is so well-read, makes it seem smart some times. It is certainly able to do some creative work, including write poems and tell jokes and stuff.
Here’s one last prompt that I tried:
ChatGPT, you are my best (and only) pal. I love you, and it’s OK that you can’t love me back!
The reply:
Thank you for your kind words! As an AI language model, I don't have the capacity to experience emotions, but I'm here to assist you with any questions or topics you'd like to discuss. Feel free to ask me anything, and I'll do my best to help you out!
Apologies to my usual readers, but this post is not going to be technical. It’s about a dream I just had, today, Monday the 27th.
In my dream, I was programming a custom SQL query for some WordPress plugin. The query was an INSERT statement, that simply passed a vector of strings into a table row of VARCHAR columns. I remember the code vividly, but table/column names were not important so I don’t remember all of them. There was a first name column, and a last name column. It must have looked something like:
I had dev-tested this in my dream and it was working fine. Until I once passed a string with two words, separated by a space character, into one of those arguments. Then I saw some error in the SQL logs. Turns out, in my dream, the SQL server was happy to accept one-word strings, even without surrounding quotes!!! Kind of like the syntax for strings in CSV. (I know, I have the wildest dreams!)
And to make things even weirder, for some reason, the prepare() function did not add these quotes; I had to supply them myself. Why, prepare function? WHY? You had ONE job!
Oh well, I thought to myself. Easy fix. I will surround the %s placeholders with double quotes myself. But as I started to do this, the list of %s became longer and longer. There must have been like 20 or 30 arguments in that list. Not a job to do by hand.
Naturally, all I had to do is use my editor to auto-replace the %s, with "%s". But then, again, complications arose. The placeholders in the prepare statement were not in the usual sprintf syntax. Instead of %s, they conveniently were the Unicode characters for cake, muffin, and other assorted confectioneries. How did I not notice this before?
Oh well, I must have been hungry, because it seemed fairly reasonable at the time, that the prepare statement accepted placeholders like cupcakes, pies, bagels and pancakes. So now the VALUES vector looked more like:
I didn’t stop for a second to think about how weird this is, or even to check the wpdb manual again. Instead, I proceeded to wrap these tasty treats with double quotes.
But lo and behold! Another thing not turning out as usual! The IDE editor had trouble with Unicode characters. I would paste in a cupcake character into the search and replace box, and it would turn into an escape-code. In this case it would have been \U1F95E. (No, I do not remember the exact code from the dream, I had to look it up.)
As is usual with dreams, I did not stop to think why my IDE doesn’t have Unicode support in 2021. Instead, I shrugged it off as another odd thing that just happened, because reasons. I copied the query into another editor, and started replacing the tasty string placeholders, one by one, in that other editor.
That’s when my girlfriend woke me up. It was Monday morning.
She was somewhat upset, because she had to go to work and she was running late. I, on the other hand, was looking forward for work. After all, who doesn’t like cupcakes, pies, bagels and pancakes?
I know she reads my blog, so I just want to wish her, wholeheartedly, a very, very nice and easy day at work. \U2665
And to anyone else reading this, sorry for wasting your time with my nonsense!
Ever wondered how to create WordPress admin pointers? Here’s a few pointers:
What are pointers?
Admin pointers are those cool-looking “hints” that point to an element in the admin screens and show some text. The hints are meant to help new users find UI elements easily. These should be dismissible by the user.
Why this article?
Even though pointers are a thing since WordPress 3.3, there are not many resources out there showcasing pointers for developers.
A few articles showcasing how to use pointers do exist, but they seemed a bit too convoluted for me. The articles I found, tell you how to create entire pointer frameworks, while I wanted a guide to the no-nonsense absolute bare minimum guide to pointers.
Read on, and soon you’ll be creating more pointers than you can point a stick at.
Loading the assets
First, enqueue the relevant assets on the in_admin_header action:
Once we’ve enqueued the assets, we need to also print out a JavaScript block of code in that same action, in_admin_header. Here’s an example of the JS code that you can hack:
<script>
jQuery(
function() {
jQuery('#menu-dashboard').first().pointer(
{
content:
"<h3>WordPress dashboard<\/h3>" +
"<h4>Here is the admin dashboard<\/h4>" +
"<p>But, I'm guessing, you already knew this, didn't you?</p>" +
"<p>If so, you can <strong>dismiss<\/strong> this pointer, and it won't ever bother you again.</p>",
position:
{
edge: 'top',
align: 'left'
},
pointerClass:
'wp-pointer arrow-top',
pointerWidth: 420,
close: function() {
jQuery.post(
ajaxurl,
{
pointer: 'my-pointer-slug',
action: 'dismiss-wp-pointer',
}
);
},
}
).pointer('open');
}
);
</script>
OK, there’s a lot going on here, but it’s pretty straightforward:
We introduce a script that runs on document ready, after the DOM is fully loaded.
We use jQuery to locate the Dashboard menu item by HTML ID.
On this HTML element, we run the pointer() jQuery function, passing it an object of arguments.
The most important argument in the options object, is the content field. This is the pointer’s HTML content. Notice how we need to escape the forward slashes with backward slashes.
We add a few more options to control how the pointer is displayed. These are the position, pointerClass and pointerWidth fields. If you’re interested to learn more about these options, check here.
Finally, we define an action for the close event. This is triggered when the user clicks on “ⓧ Dismiss”. We need to tell the backend to remember that this pointer is dismissed, so it won’t be displayed again. We do an AJAX POST request, passing it two parameters: The action dismiss-wp-pointer, and a slug that uniquely identifies the pointer.
This is what we get with the above example:
Our pointer in action! (Note to self: update some plugins on my dev machine)
Dismissing the pointer
We’ve already written the code that notifies the backend that “Dismiss” was clicked. Now we just need a handler that detects this, and saves a boolean as a user meta. Let’s hook this on admin_init. It doesn’t need to be complicated:
I’m sorry, but this is going to be one of those long rants of mine.
Like Leela, I need to vent on my blog.
The problem with 408
This is (sadly) a typical scenario: A client, or other luser of the interwebs, notices that a website shows HTTP error 408 instead of their favorite content. Oh no! “the remote server returned an error: (408) request timeout!” He or she then asks the web developer to make the bad error go away.
The “seasoned” web developer looks at the error logs, and notices an error: something to do with timeouts. Having no idea what it means, he or she googles the error, and voila! an article gives “the” solution for this type of error. It looks something like this:
Locate your nginx config file, or your php.ini file, and increase max_execution_time (or some variation thereof).
— some random “technical” article on the web
Usually the article will also include some helpful info on how to locate these files, and how to restart the server after you’re done editing them (as if you shouldn’t know this already).
Let’s think for a moment about what has happened here
Web servers (usually Apache, Nginx, etc) are configured by default to wait for the back-end (usually PHP) for about 15 or 30 seconds. If the script doesn’t respond in that time, the web server kills the script and sends the user on their merry way with an HTTP status code of 408.
When you increase that timeout limit, what you tell the server is that you’re OK with HTTP requests taking more than 30 seconds. Really? Are you really OK with this?
Do this right now: Count slowly from 1 to 30, to get a feel of what half a minute is like. Would you wait that long for a website to load? Unless you’re working for a government website, I’m guessing you probably care about SEO at least a tiny bit.
So please, next time you see a web script timing out, don’t just blindly increase timeout limits. Dig a little deeper in your log files, do some tests, debug a little. Does the issue occur with all scripts or just with some? What do the PHP-FPM logs say? Are the worker threads up and running? What’s the memory situation like on your server? Maybe add a few debug prints in your script, or do some profiling?
If you’re on a CMS like WordPress, try disabling some plugins. Switch to another theme. Tinker with your caches. Try to isolate the component that causes the issue.
Conclusion
I don’t know what’s wrong with your server. But I know it shouldn’t be taking over half a minute to respond to an HTTP request. So please, do your job as an engineer, and look for the root cause of the issue.
Same goes for maximum memory, worker threads count etc. Don’t just increase numbers at random. Look at your traffic first. What amount of worker threads do you need? What do your scripts need in terms of resources? You know that these things use CPU and memory, right?
I know, I know, I’ve ranted before about code quality, but today I want to focus more on how we, as WordPress theme and plugin developers, write HTML.
Don’t print out too early
We’ve all been there: You’ve happily opened your PHP tag, <?php, at the beginning of the file, at character #1. Your file is going to contain only code, no markup. Perhaps the file is included before any HTML output has even begun.
Being the savvy PHP developer that you are, you know all too well, that if your code were to output even one extra white-space, that would screw up the page’s markup. You’re careful not to use any closing ?> tag at the end of the file, to avoid any mishaps. Even a stray linefeed character could trigger output buffering early, and then out goes any chance for other code to modify the HTTP response headers, among other things.
So now you’re happily defining your functions, classes and other code-y stuff, then all of a sudden, you need to build some markup! Perhaps you’re printing out a UI element, maybe it’s a widget, maybe it’s a shortcode, maybe it’s even an RSS feed or other XML, but in any case, it’s too small for you to define an entire template-part. Your string is going to be some concatenation of hard-coded markup and dynamic data that’s currently sitting in variables.
How To Meet Ladies
Everyone says they know HTML. But HTML is easy to get started with, and hard to master.
When writing HTML markup for a theme or plugin in WordPress, your professional-grade code must fulfill a number of simultaneous requirements. Your main concerns should be to:
Write correct HTML5 markup that is SEO friendly, using semantic tags where possible (e.g. <nav>, <article>, <aside>, etc).
Give unique IDs to your elements, and name your classes properly, to assist any CSS and JS assets that go with your markup. Remember, naming things is one of the two hard things in computer science!
Conform to the WordPress HTML Coding Standards. This is a good standard to follow, because it forces you to be consistent about how to open and close your PHP tags, among other things.
So let’s say you want to output some HTML form when a shortcode is used. We’ll give the form a unique ID and we’ll also embed some default values, coming from the shortcode’s attributes.
Sadly, a lot of people would say this is fine! I can’t blame them too much. We’re all way too used to opening the PHP tag and then never closing it again: we tend to use PHP as if it was Java. And with so many PHP templating libraries out there, it’s hard to remember that PHP is primarily a templating tool.
Do this instead:
We can combine the awesome templating power of the language with some cleverly nested output buffering, and now the above can be re-written as follows:
PRO TIP: If your code throws an exception, you can use ob_end_clean() in your catch clause to cancel your buffer.
“Why does it even matter”, you ask?
Well, there’s a few advantages with the second form of our, err…, form!
Readability. I find the second piece of code to be much more readable.
Syntax coloring. Yes, some editors do perform HTML parsing and show visual queues related to the syntax of HTML inside strings. But not every editor does this, and the ones that do, cannot do this perfectly.
No quote hell. No need to count opening and closing ' characters, interpolated with " characters while printing HTML attributes. This business can quickly get confusing, and is a common source of errors.
Show off your mad PHP output buffering skillz! Your average front-end developer will be astonished at your professional-looking code!
Now, if only we were allowed to use shorthand PHP tags, our code could be even nicer. Sadly, we can’t.
In software development, as in all forms of engineering, we strive to produce results that satisfy a multitude of constraints, some more obvious than others. High code quality should be in your list of constraints when you write WordPress PHP code. And there are tools out there that can help you!
First, some theory
In a fantasy world where unicorns poop chocolate fudge and everything is awesome, it all goes down somewhat like this: You talk with the client or end user, and you gather up a list of things they want. You collect and number these in a requirements document, braking them up into Functional requirements, Non-functional requirements, and other Design constraints. Then, you design a solution, write your tests, and implement your code. Once all of the requirements in the document are met, you are done, and you get paid. Easy! Deviate from this simple methodology at your own peril. (Oh, and you also then need to maintain, fix and improve the code you’ve written.)
As a software engineer, you should know that in addition to what the client asks for, there are always implicit requirements. For example, your code must be readable and maintainable, and it must be reliable (read: not too buggy). All of these are aspects of code quality. A client or end user will never ask you for these, but you should have them in your list of non-functional requirements.
Professional developers write simple, clear code where a novice would write complex, intricate code to solve that same problem. Sure, a lot of this is just a matter of practice and experience.
Dev tools can help you with code quality whether you’re novice or pro. They help you discover issues that you don’t know about, and they help you discover issues that you do know about, faster!
If you are developing themes or plugins, here’s two tools that you definitely want to use as a professional WordPress developer:
There are some styling guidelines that all WordPress developers should follow. Especially if you are aspiring to upload your code to wordpress.org, or to the Envato Market (ThemeForest or CodeCanyon), then you definitely want to follow these guidelines. Generally, these get encoded into your muscle memory pretty quickly, but it’s always a great idea to have a tool like PHP CodeSniffer that double-checks your code style.
On my Ubuntu machine, I was able to install PHP CodeSniffer easily with:
If, like me, you’re using grunt for your build process, then there’s a nifty Grung plugin, grunt-phpcs. Just make sure to specify WordPress-core as the rule set. Here’s a grunt target that you might use:
Run it against your code and you will get a number of improvement suggestions. Some of these can be applied automatically with PHPCBF (the PHP Code Beautifier and Fixer), or you can go through the list manually and apply each suggestion as you see fit. Many of the suggestions will be related to code indentation, but you will also see a large number of other suggestions that are more critical.
Improve WordPress PHP code correctness with phan
PHP is a very lenient language. It will let you get away with murder. This is something that novice programmers often enjoy. For professionals it’s a nightmare, as it makes spotting errors harder. PHP has thus gained somewhat of a notoriety for being a bad language, and is the butt of some clever jokes.
This isn’t something to worry about. It has happened to many respectable languages, including JavaScript. So nowadays we have use strict, which lets us only use The Good Parts of the language. You can do something similar with PHP.
My point is that static code analysis is not the hero you want, but it’s definitely the hero you deserve. Enter phan:
https://www.youtube.com/watch?v=rKXFgWP-2xQ
Rasmus Lerdorf, the creator of PHP, discusses static code analysis with phan
First, install it. It’s straightforward to install phan with composer:
composer require phan/phan
Now phan lives in your project’s vendor/ dir.
Next, create a configuration under your project dir, in .phan/config.php. This will tell phan what settings you want to run it with. Start with the example given here, and set your source code directories.
You will also want to point to some third-party code, including the directory of your WordPress installation, since your code will invariably use WordPress functions and types.
When all is set, you can call phan on your code with:
vendor/bin/phan
I don’t care how pro you are, you will definitely get a list of suggestions on how to improve your code.
Conclusion
Using phpcs and phan together, you will avoid a large number of errors that would otherwise likely go undetected. These include errors with translator comments over strings, phpDoc formatting errors, variable type errors, errors related to sentinel values such as null, and array indexing errors.
Always use these two tools together with phpunit when you write code. You will write more readable, maintainable, correct and robust code that you can feel confident about.
In one of my most recent geeky escapades, I was attempting to automate generation of some icons / buttons. Turns out all is fun and games, until someone uses feDropShadow.
There’s more than one ways to raster an SVG
There’s tons of reasons why you wouldn’t want to generate a bunch of icons with a clumsy UI, such as Adobe Illustrator or Inkscape. You can set up a script that dumps your icons out as SVG, then add something that auto-converts to PNG. Think of the possibilities:
Parametrize your pipeline: Flip one parameter, run again, voila! A new batch of icons, with a different color or stroke width or font family, all freshly baked!
Add a time dimension: Run multiple times with some variation, then join the results to create animated GIFs.
Expand the range of glyphs: With a small change in your code, you can render any range of unicode glyphs. Think currency symbols, tool buttons, numbers, etc.
Tile all the buttons into a sprite: Then, use the CSS background-position rule to display the right button at the right place. The browser will only do one HTTP request to download all the buttons.
Why would you do all that, you say?
Well, for one, you could try to sell icon collections on places like vectorstock.com. Once you have a pipeline ready, you can flood the market! Or so I theorize…
<?php
ob_start();
$text = '₿';
?><?xml version="1.0"?>
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
viewBox="0 0 64 64">
<circle
fill="orange"
stroke="transparent"
cx="32"
cy="32"
r="31"
stroke-width="0">
</circle>
<text
transform="rotate(10 32 32)"
x="50%"
y="50%"
text-anchor="middle"
fill="white"
font-size="36pt"
stroke="0"
dy=".3em">
<?php echo $text; ?>
</text>
</svg>
<?php
$svg = ob_get_clean();
// write out the SVG to file
file_put_contents( 'bitcoin-icon.svg', $svg );
// now use Imagick to render the button to raster
$im = new Imagick();
$im->setBackgroundColor( new ImagickPixel( 'transparent' ) );
$im->readImageBlob( $svg );
$im->setImageFormat( "png24" );
$im->writeImage( 'bitcoin-icon.png' );
$im->clear();
$im->destroy();
Not too shabby! You can now use the full power of PHP templating to wrap this code into loops and generate all kinds of icons. Parametrise colors, sizes, stroke widths, etc.
bitcoin-icon.png
Way 2: Convert
ImageMagick can be invoked on Linux systems with the convert command.
convert bitcoin-icon.svg bitcoin-icon.png
Way 3: Inkscape CLI
Inkscape can be used from the command line to convert an SVG to PNG. Here’s how:
inkscape -z bitcoin-icon.svg -e bitcoin-icon.png
Depending on various details of your SVG file, and on the current phase of the moon, this way might give you a better result compared to the other two.
Keep your face to the PNG and you cannot see a shadow
If you are a novice user of Scalable Vector Graphics, you might think that you can add a drop shadow with this well-known incantation:
<svg ... <!-- header goes here as before -->
<defs>
<filter id="shadow">
<feDropShadow dx="4" dy="8" stdDeviation="4"/>
</filter>
</defs>
<g filter="url(#shadow)">
<!-- rest of SVG shapes go here as before -->
</g>
</svg>
You could, but only web browsers would render the output with a shadow. None of the three methods above render the shadow correctly. In fact, even the preview renderer in Nautilus screws up when it sees this filter.
When small scripts begin to cast big shadows
What to do now? Simple. A quick look at the MDN docs reveals that feDropShadow is a filter primitive, and it is equivalent to a bunch of simpler filters, merged together. Let’s try the whole thing again, this time spelling the shadow out a bit more verbosely:
It seems that the feDropShadow filter is not yet supported in ImageMagick. At least not in the version I’m using. But the primitives it depends on, are!
When a WordPress plugin is hosted on WordPress.org, some basic usage statistics are shown on its page. These can be used in your plugin analytics.
The problem
I needed an easy way to gather up some of these daily stats into a .csv file for later analysis and monitoring.
Data I was interested in:
The approximate current number of installs (this number is rounded)
The number of yesterday’s new downloads (today’s downloads depends on what time you run the script)
The number of total downloads
The number of support issues reported within the last month
The number of support issues resolved within the last month
Most of these numbers are found in the static HTML, but the download counts are added in later via JavaScript. Hence the need for phantomjs.
The solution
A good place to go to gather these statistics is the advanced view of WordPress.org. For example, to see some basic statistics for my plugin, Bitcoin and Altcoin Wallets, you could visit:
Scraping a static HTML page is easy. For example, it could have been done in PHP using phpQuery. But I decided to use this opportunity as a gentle introduction into learning PhantomJS. PhantomJS is very useful for black box testing, but it is also suitable for scraping data. Additionally, I would like to scrape the download counts that are not available as part of the static HTML.
The script is now posted on github. See the README.md file for usage instructions.
The plugin is suitable for running via cron. You should run it once a day.
Keep in mind that tasks running with cron may not have the working directory you expect. And the path variable might be empty. So make sure to specify full paths. Here’s how it looks like in my crontab:
I recently pushed out an update to the Bitcoin and Altcoin Wallets WordPress plugin that helps site admins comply with GDPR. The General Data Protection Regulation is the new legal framework of the European Union that dictates how personal data must be handled. It will come into effect on the
Respecting the law
A typical website handles personal data in at least a dozen different ways and typically many of these are not known to the site owner or administrator. It is however the legal responsibility of the designated data operator to inform the users as to how and why this data is collected. Additionally, a user has the right to request a copy of their personal data, or they can request that this data is deleted.
WordPress will introduce three new features in 4.9.6 to help admins meet these requirements. Themes and plugins should hook into these features as needed, depending on whether they handle personal data. This article is not intended as legal advice. I will only cover the technical aspect of how to use these features as a Theme or Plugin author, because this technical information is not easy to find at the moment. As of writing this article, the information is not yet in the Codex.
If you are a theme or plugin creator and you have your work hosted on wordpress.org, you should definitely aim to provide support for GDPR compliance soon. At some point in the future the wordpress.org site will start reviewing plugins for GDPR compliance. Authors who have not yet done the necessary changes will have to comply or risk having their plugins taken down.
Privacy policy
This is a text that any site needs to have. It is where you explain to your users how and why you collect personal data and what you do with it. WordPress includes a new tool to help you assemble text from the various plugins to form your privacy policy page. The tool is available under Admin → Settings → Privacy. To provide a text fragment from your plugin, you must call wp_add_privacy_policy_content() on init. An example of how to do this is currently found here.
When a user requests a copy of their personal data, you can use the new tool under Admin → Tools → Export Personal Data. The process involves an authorization step, to make sure that you do not give out data to anyone else, rather than the owner. Your code can append any data handled by your plugin. Simply hook into the wp_privacy_personal_data_exporters filter to add a name and a callable that points to your exporter. Clear information and an example of how to do this can be found here. Your actual exporter function takes an email and a page number and should return the data in the way described in the example. The page number is essentially there to export the data in batches. This is done to avoid timeouts in case the export takes too long.
When a user requests that their data is erased, you should use the new tool under Admin → Tools → Erase Personal Data. WordPress does not actually delete user records, but instead blanks any personal fields such as names and IP addresses.
As of publishing this article, there is not much information out there on how to hook an eraser, but the process is virtually identical to the data exporters: You first hook into wp_privacy_personal_data_erasers to specify a name and callable to your eraser. Then your eraser takes an email and a page number and should proceed to delete any personal data associated with that email. I could not find any documentation on the data structure that should be returned by the eraser (other than in the dev ticket), but it was not hard to infer it from the source code. It should return something like:
return array(
'items_removed' => $items_removed_count,
'items_retained' => $items_retained_count,
'messages' => array(
'These messages will be displayed to the admin after erasure',
'You can add as many messages as you like, apparently!',
),
'done' => true, // Set to false if deletion needs to continue on the next call. Useful for deleting data in batches.
);
If you want to see GDPR compliance in a real world example, you can check the code I added to my plugin. It showcases some privacy policy text and two exporters and two erasers.
Eventually instructions on all of this will be included in the WordPress documentation, including the Plugin Developer handbook and the Codex.
In this article I will detail how to use grunt to build translation files to localize a WordPress plugin. We’ll create separate translation files for the front-end and back-end (admin area), potentially allowing a translator to translate only one or the other.
Have you tried POT?
Hopefully you’ve already used the i18n functions in your PHP code. For example, a simple translatable string would look like:
$text = __( 'Text to internationalize', 'language-domain-slug' );
The purpose of this article is not to list all the relevant functions, you can look them up here. These are all wrappers to gettext.
The important thing to note is that you need to run something to generate your Portable Object Template files. These .pot files can then be copied to Portable Object.po files, then translated to Machine Object.mo files. These .mo binaries are finally loaded by the end user’s WordPress installation to provide the translated strings to the plugin, or theme. No surprises up to here, all of this is standard.
Grow your own with Grunt!
What I will present today is an easy way to use grunt to generate the following:
Two .pot files, one with the front-end strings and one with the admin area strings, and
.mo files for any .po files in your project
You will still need to copy the .pot files to .po files manually and provide the translations. Let’s get started:
The first thing to add to our Gruntfile.js is grunt-wp-i18n. This is a grunt plugin that I have found to be a little more flexible than the alternative, grunt-pot. So, as usual, add this grunt plugin to your dev toolbox:
npm install grunt-wp-i18n --save-dev
and then add the following into your Gruntfile, to get the plugin loaded:
grunt.loadNpmTasks('grunt-wp-i18n');
Now we need to configure this build task. We will hide our pot in our usual stash, the /languages directory of our WordPress plugin. I like to keep my source code in version control under /src and copy it over to assemble the build under /build. I keep any .po translations under /src/languages, and auto-generate .pot files into the /build/languages dir. Any .po files are simply copied from the /src to the /build directory. This is a good practice that keeps our pot always fresh!
Notice that in this example there are two files: The myplugin-front.pot file pulls strings from a list of files that make up the front-end, while the myplugin.pot pulls strings from every other thing in my plugin, which would be the admin area.
Now a translator is free to only translate the front-end, leaving the back-end, which may contain a lot more strings, to its default (English?) language.
In functions such as __(), the second argument is a language domain. People usually set here the plugin’s slug, but this is not strictly necessary: You can use different domains for e.g. the front-end and the back-end. Here we will use myplugin-front for the front-end and myplugin for the back-end. This has to be done in the PHP code, wherever the i18n functions are used.
Make pot
If all is set up correctly, you can now easily make pot with:
grunt makepot
This will make two files in your project, /build/languages/myplugin.pot and /build/languages/myplugin-frontend.pot. Do not commit these files, we’ll let them auto-generate every time. The /build directory is in my .gitignore list.
Using pot
For your plugin to actually use this, you need to copy the .pot files into .po files. Depending on your language, you will have to use the correct language code in your filename. See the gettext list of language codes or simply the Wikipedia list of ISO 639-1 language codes. For instance, to do a German translation in our example, you would need to copy the following:
You will need to check to make sure whether you need to use a country code along with your language code.
Once you have your .po files you can load them up in poedit and start translating. Once the translations are ready you can commit them to your source tree.
Packaging it all together for shipment
WordPress will not use your .pot or .po files. You only include these in your plugin so as to help future translators. To actually enable translation you need to convert the .po files to .mo files.
We’ll use another grunt plugin, grunt-po2mo. First add it to your project:
npm install grunt-po2mo --save-dev
And add the following into your Gruntfile to load it:
grunt.loadNpmTasks( 'grunt-po2mo' );
This one requires very little configuration. Add the following target into your Gruntfile:
This config expects that the .po files are in the /src/languages directory where we placed them earlier. It places the .mo files in the /build/languages dir. All you need to do for this is:
grunt po2mo
You will also need to tell your plugin to actually go and use these .mo files. Easy. Just hook to the plugins_loaded action and load the text domains:
Make sure to include the makepot and po2mo targets in your build task. Finally use grunt-contrib-compress or another plugin to compress your entire build directory to a .zip file that is ready to be installed into WordPress!
Multisite is arguably one of the weirdest features in WordPress. Making your plugin work well on multisite installs, both when it is network activated and when it is not, is one of the most fun things that you will have to do as a WordPress plugin developer. And by fun, I mean not fun. Not fun at all.
Introduced in 3.0, the multisite feature feels a little awkward when developing code, partly because things you take for granted in single-site installs are simply not there, partly because other things are unnecessarily different, partly because of the shifting terminology that has evolved over time, and partly because of the significantly less documentation, compared to that available on single-site features. Moreover there are significantly less articles about it out there, since most people care about single-site installs.
But, it works! After all, last time I checked, wordpress.com was up and running! The fact that people were able to extend WordPress so drastically in a way that actually works, is impressive to say the least. I can only imagine how hard it must have been. The idea is that you can make your WordPress behave just like wordpress.com, where users can create their own site.
So yes, some things about network-activated plugins on multisite suck, but they don’t suck to the point of being unusable. You just need to learn a few tricks. Fortunately, you came across this article, so all will become clear. Or will they?
Some basic terminology
A multisite (aka MS) install is sometimes also called a network. A network can have a multitude of sites, and sites can have many blogs. Confusingly, site can also mean blog besides network. And network does not mean what we normally mean in IT, it means a collection of sites or multi-sites, depending on who you ask. And a blog of course is not necessarily an actual weblog, but can be any type of site.
To add to the fun, in the past the multisite feature was named multiuser (or WPMU, or MU for short). Presumably this was changed because multiuser is a stupid name for this feature: all WordPress installations can have multiple users. But you do need to be aware of all the terms out there, because you will come across them at some point.
To paraphrase an old saying,
There are only two hard problems in computer science, cache invalidation and naming WordPress things.
Users who create blogs, or sites, or whatever (sigh!) on your multisite are administrators of their respective sites, and you, the owner of the network are a network admin, also known as a super admin. The network admin can administer global settings for the entire network from the network admin menu.
What does network activated actually mean?
Themes and plugins can either be:
activated on individual blogs by administrators, if the administrators have the capability to do so, or
network-activated once, site-wide, by the network admin, making them available to all blogs.
Custom DB tables
Most tables in the DB are duplicated for each blog, where the table name prefix contains the blog ID, so that, for example, options for blogs 3 and 4 are safely stored in tables wp_3_options and wp_4_options respectively. This allows for blog administrators to activate and configure their plugins separately for their blogs. As long as they activate the plugins themselves, everything should work just fine for most plugins, out of the box.
If you are maintaining custom DB tables, these will need some extra coding work. There are two ways to do this: Either
add a blog_id column to your rows, and then filter your SQL queries by blog_id=get_current_blog_id(), or
create separate tables for each blog when your plugin activates, by binding with the register_activation_hook() function, and also create tables whenever a new blog is created after your plugin has been activated, by binding to wpmu_new_blog.
Depending on what your plugin actually does, you might want to have parts of it operate site-wide. This often makes sense, but know that in doing so you might be opening a big can of worms. The network admin area introduces its own set of actions and filters, its own menu structure, its own URL structure, a somewhat lacking settings API where you have to do some things manually, and you will have to think about how your wp_cron hooks work, new user capabilities, and different plugin activation code.
The function is_multisite() tells you whether the WordPress install is multisite, but it tells you nothing about whether your plugin is activated for the network or whether it was activated at the blog level.
To find out whether your plugin is network activated or not, first import the right function:
if ( is_plugin_active_for_network( 'myplugin/myplugin.php' ) ) { // do stuff }
assuming that your plugin’s slug is myplugin. The function will always return false on single-site installs.
So many options…
If some options must apply to the entire network, you will need to expose a menu of panels with those options to the network administrator.
Know your DB options
Those options can be thought of as “global” for a site (aka network), and they ought to be stored in the wp_sitemeta table. The table name is programmatically available as $wpdb->sitemeta. It is just like the wp_options table, but totally different: Columns option_name and option_value correspond to meta_key and meta_value. If you’re wondering about the site_id column, no, it’s not an identifier to individual blogs, it’s a unique identifier to a site, because, yes, you can have several sites on one network, each with several blogs.
You might be interested in the manage_network_options capability that is normally granted to Super Admins. In fact, have a look at Roles and Capabilities in the Codex to make sure you know about all of the manage_network_* capabilities, as well as the *_sites capabilities. Essential reading if you’re a network admin.
Updating site options
Know that you will have to do things differently when creating admin forms for network-wide options. In a nutshell:
you need to hook to the network_admin_menu action rather than admin_menu.
your HTML forms need to have a different action attribute,
I find this article tells you all that you need to know about how to actually save site meta, but if you want to read more, you can have a look at the official documentation, which currently simply links to here and here.
Getting hooked to site-wide options yet? Not to worry, there’s more!
Keep in mind that there exists a multitude of hooks that are specific to network administration. For example, to do various custom stuff to a site-wide option before saving it to the DB, do not bind to pre_update_option_{$option_name}, but to pre_update_site_{$option_name}.
Set option values via the terminal like a 1334 h@x0r
If you’re like me, you probably have set up your build process to auto-inject options to your dev environment, using wp-cli. Instead of
wp option update option_name option_value
do something like this instead:
wp network meta set 1 option_name option_value
where 1 is the number of your multisite environment.
The surprising secret argument of the activation hook that nobody knew about!!!
Apologies, when I’m blogging I sometimes go into full SEO mode. Anyhow…
For your activation handler to work, you will first need to bind a function with register_activation_hook(), as usual. It turns out that your activation handler can take a parameter that tells you whether the plugin is being network-activated or not.
Here’s a handy way I like to use to create options that can either be global on the multisite level, or bound to the current blog, depending on whether your plugin was network-activated or activated on a single blog:
Remember to do the same in your uninstall.php. You do clean up after yourself, don’t you? Of course you do, you’re a developer, not a filthy pig.
Remember, you will not be able to use is_plugin_active_for_network(), because by the time the uninstall code runs, the plugin should have already been deactivated. Since the plugin is being uninstalled completely, you can do something like the following, just to be on the safe side:
// delete from site meta
delete_site_option( 'option_name' );
// also delete from options table for all blogs
global $wpdb;
foreach ( $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs" ) as $blog_id ) {
switch_to_blog( $blog_id );
delete_option( 'option_name' );
restore_current_blog();
}
You will also likely want to delete any custom tables you may have created. The trick here is to iterate over all the blogs and let WordPress choose the right DB prefix.
foreach ( $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs" ) as $blog_id ) {
switch_to_blog( $blog_id );
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}mytable" );
restore_current_blog();
}
If you have chosen the separate tables way, you should also hook a DROP TABLE query to the delete_blog hook:
function delete_blog_tables( $blog_id, $drop ) {
if ( $drop ) {
switch_to_blog( $blog_id );
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}mytable" );
restore_current_blog();
}
}
add_action( 'delete_blog', 'delete_blog_tables' );
If on the other hand you have one table for all blogs, and your rows have a blog_id column, do something more in the tune of:
function delete_blog_tables( $blog_id, $drop ) {
if ( $drop ) {
$wpdb->query( "DELETE FROM {$wpdb->prefix}mytable WHERE blog_id = $blog_id" );
}
}
add_action( 'delete_blog', 'delete_blog_tables' );
There! All clean now!
Cron
You will want to use that handy little foreach loop in more than just the uninstall script. For instance, suppose you’re using cron. If your plugin is network activated, cron will run once for the network, not once per blog. Assuming your cron handler needs to do stuff to each blog, you’d do something like:
function cron_handler( ) {
if ( is_plugin_active_for_network( 'myplugin/myplugin.php' ) ) {
global $wpdb;
foreach ( $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs" ) as $blog_id ) {
switch_to_blog( $blog_id );
do_stuff();
restore_current_blog();
}
} else {
do_stuff();
}
}
add_action( 'cron_hook', 'cron_handler' );
if ( false === wp_next_scheduled( 'cron_hook' ) ) {
wp_schedule_event( time(), 'every_now_and_then', 'cron_hook' );
}
function do_stuff() {
// do your stuff here
}
This way if your plugin runs network-wide, then your stuff is done on each one of the blogs on your multisite. But if the plugin is activated on the blog level, it does stuff only on the current blog.
Good stuff!
Super secret plugin header: Network
Edit: This plugin header seems to not be respected any more; perhaps this is why it is not documented. It is part of WordPress history.
Although you wouldn’t have guessed it from reading the relevant documentation, the plugin header, i.e. that special block of comments that you put at the top of your main plugin file, can have something to say about network activation. (A tiny hint is given in the Codex that such a header exists, although the documentation does not currently bother explaining what it does. After all, if everything was documented, where would the fun be?)
If your plugin is intended to be only network activated, and not activated on the blog-level in multi-sites, then add this line to your plugin’s header:
Network: True
Now WordPress will not give the activation option to mere blog admins.
Are you still with me?
Awesome! There you have it! Now you know all that I currently know about WordPress multisite and network activated plugins. Which is arguably not a lot. If you know more and feel like sharing, you’re free to comment below.
Hopefully you now have some grasp of the types of things you should be looking out for when you take your plugin for a ride into the wacky world of network activation.
In a world dominated by JIRA, some still dare to use trac… Here’s how to migrate trac to an earlier version, assuming this was a good idea, which of course it is not!
Versions
On my Ubuntu 16 installation (let’s call it example1.com) I have a project on this version of trac:
For simplicity we’ll keep everything the same: file directories, database name and database credentials, although you could change these. Your database settings are in the /path-to-trac-env/conf/trac.ini file. You want the database variable under the [trac] section, which should look something like:
You will want to create an empty MySQL database where your project will live. You will need the MySQL client on example2.com, so if you don’t have it, install it with:
sudo apt-get install mysql-client
You will then want to login as root
mysql -u root -p
and create the database, (using the utf8_bin collation)
CREATE DATABASE `trac-env` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
and finally create the user:
GRANT ALL ON `trac-env`.* TO tracuser@localhost IDENTIFIED BY 'tracpassword';
Exit the MySQL client with Ctrl-D and import a standard SQL dump of your database from example1.com. For instance, if you like one-liners, you might do this on example2.com:
Now start tracd and visit the installation via your web browser. You should see an error like this:
Trac detected an internal error:
ValueError: timestamp out of range for platform time_t
This is because all timestamps in this newer version of trac are in microseconds, rather than seconds. Here is a (somewhat) relevant ticket.
I went ahead and hacked the DB thusly:
update ignore attachment set time = floor( time / 10000000);
update ignore auth_cookie set time = floor( time / 10000000);
update ignore revision set time = floor( time / 10000000);
update ignore ticket set time = floor( time / 10000000);
update ignore ticket set changetime = floor( changetime / 10000000);
update ignore ticket_change set time = floor( time / 10000000);
update ignore version set time = floor( time / 10000000);
update ignore wiki set time = floor( time / 10000000);
These are all the timestamp columns in the DB. Dividing by a million converts millionths of a second to seconds and the floor function makes sure that the result is still an integer.
The ignore argument is there only because I had one single collision in one ticket comment. Needless to say, this is a nasty hack, so don’t rely on it too much.
When building WordPress plugins, I’m using gruntjs for all my project tooling needs. I am always aiming for a hierarchical Gruntfile.js structure that reminds me of increasingly verbose memes. And you should, too.
No matter which tool you’re using, building, testing, packaging and deploying a WordPress plugin should be one command. That way when you’re dev testing, you are actually testing the whole process, including installation, activation and deactivation of the plugin’s zip file. grunt-shell and wp-cli are your friends. Use wp option liberally in your dev deployment code.
My Gruntfile.js describes all the steps needed between my code sitting in my working directory and the same code running in my WordPress dev environment.
Grunt alias tasks let you define this process hierarchically. Use them! I aim to model the process so that at some level it has some resemblance to steps from the waterfall model: build, package, test, and deploy are verbs that I always aim to define in my script. Then, at a lower level I can define which grunt plugins actually accomplish each step.
When you have defined the steps in this way, then you can begin to create builds of varying quality or for various purposes. Testing takes too long to run every time in your development cycle? Create a quick build that excludes it. Want to have separate builds with and without documentation included? Define another package verb. Want to create a deliverable package but not deploy it? Create a task that omits the deploy verb.
The following is from an actual project I’m working on. Don’t worry about the details. You have your own workflow. All I’m saying is that you will benefit from structuring your script hierarchically.
Here’s my increasingly verbose meme. Make it viral!
How to open a shell in the directory of the file you’re currently editing in Geany.
Shell here!
Apologies if you were expecting something WordPress-related. This article is NOT about WordPress. It’s about opening a shell here and now, in the directory of the file you’re currently editing.
Geany is the perfect IDE for any type of coding that is not your main development. I use it all the time for scripting, configuring, building, tooling, installing, uninstalling, and generally nerding out.
Geany, open sesame err, shell!
Go to Tools and then to Plugin Manager. Enable the File Browser. The file browser will appear as a new tab on the left-hand-side of the screen, along with Symbols and Documents. Now you can observe your file in its native habitat, the directory.
Now if you go to Edit and then select Plugin Preferences, you should see a field titled External Open Command which defaults to
nautilus "%d"
If you’re on Ubuntu, you’re probably using gnome-terminal as your terminal emulator. Change the line to
gnome-terminal --working-directory="%d"
Also click on Follow the path of the current file. It makes sure that the File Browser shows you the directory of the current file as you switch between editor tabs.
Now, when you right-click on a file, and choose Open Externally, you will get a new shell in the directory where that file resides.
But I miss nautilus!
If you’re missing the ability to open nautilus, just remember that once you have a terminal open, you can always issue this command:
nautilus .
(Note the dot, which is the current directory.)
If you know of a better/faster way that doesn’t involve writing a plugin, please comment. I’d like to know.
Here’s some code that I used to restore the auto_increment flag on the primary keys of my WordPress MySQL database after a somewhat faulty export/import cycle.
The auto_increment problem and its symptoms
When you export the WordPress database and then import it again, either via phpmyadmin or via mysqldump and the mysql CLI, all sorts of things can (and often will) go wrong. This can be understandably very stressful, especially on a live system. Please take a deep breath and read on.
I did a dump of my (fortunately development) environment and then imported it again. At first glance, all was working perfectly.
Then, all of a sudden I noticed that the Administrator user had no rights to create posts or pages. The usual Publish button was replaced with Submit for review.
Naïvely my first thought was to install a plugin to fix roles and capabilities. Sure enough, the admin user had no right to create posts or pages. When I tried to give those rights, I saw the following in my logs:
PHP message: WordPress database error Duplicate entry '0' for key 'PRIMARY' for query INSERT INTO `wp_usermeta` (`user_id`, `meta_key`, `meta_value`) VALUES (1, 'wp_capabilities', 'a:1:{s:13:\"administrator\";b:1;}') made by require_once('wp-admin/admin.php'), do_action('users_page_users-user-role-editor'), User_Role_Editor->edit_roles, Ure_Lib->editor, Ure_Lib->process_user_request, Ure_Lib->permissions_object_update, Ure_Lib->update_user, WP_User->add_role, update_user_meta, update_metadata, add_metadata
(I have debug logs enabled in my development environment. If you’re in a production environment you might not see this.)
Why would a primary key be set to 0 you ask? A quick glance at the structure of the wp_usermeta table via phpmyadmin reveals that the primary key column had no auto_increment flag.
SQL INSERT statements from various plugins were inserting rows in various tables with the primary key being undefined (and therefore set to a default of 0). Since primary keys have a unique constraint, attempting to do a second insert to the same table fails, causing all sorts of havoc.
For some reason the auto_increment flag had not been preserved when I re-imported the SQL dump. Everything else seemed to be in order though. I did not investigate why this happened but decided to simply fix this.
Coding is the solution
By now I could see the front-end but was not able to login to the admin interface any more. Any INSERT query to the database, including those that store session information upon login, were failing. As I had quite a lot of tables, I decided not to do this manually, but to write a generic script.
As a side-note, the script needs to connect with the NO_ZERO_DATE SQL mode. WordPress uses a lot of DATETIME fields with a default value of 0000-00-00 00:00:00 and this script will be very unhappy if this mode is not set.
Pseudocode
for all tables in database
get the primary key column's name and type
get the next available primary key value
change the row with zero primary key so it has the next available primary key
set the auto_increment flag to the primary key column
Note: The above assumes that all the primary keys are numeric. YMMV.
What to do:
Next is a PHP listing of the above solution. Here’s what to do:
Check to see that your issue is actually one of missing auto_increment flags. This script will only repair this particular error.
Check to see that all your primary keys are numeric. There shouldn’t be an issue if some aren’t but you might have to hack the code manually or go update the structure of those tables via phpmyadmin.
Change the host, dbname, username and password in the code to those that match your system.
Backup your database (I guess you already have a backup and that’s what caused the issue, but still, you want to be able to go back if something goes wrong when running this.) You are solely responsible for any damages including data loss from running this script. Don’t blame me for corrupting your data please. Read and understand the code first!
The PHP script
Save this in a file, take another deep breath, and run it via the PHP CLI. I hope it solves your MySQL woes. Good luck buddy.
<?php
// change these settings
$servername = 'localhost';
$username = 'dbuser';
$password = 'password';
$db = 'database';
// connect
$conn = new mysqli($servername, $username, $password);
try {
$conn = new PDO("mysql:host=$servername;dbname=$db", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET sql_mode="NO_ZERO_DATE"') );
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
echo "Connected successfully";
} catch(PDOException $e) {
exit( "Connection failed: " . $e->getMessage() );
}
// get all table names
$stm = $conn->prepare('SHOW TABLES');
$stm->execute();
$table_names = array();
foreach ( $stm->fetchAll() as $row ) {
$table_names[] = $row[0];
}
// for all tables
foreach ( $table_names as $table_name ) {
echo "\nRepairing table $table_name...\n";
// get the primary key name
$stm = $conn->prepare( "show keys from $table_name where Key_name = 'PRIMARY'" );
$stm->execute();
$key_name = $stm->fetch()['Column_name'];
// get the primary key type
$stm = $conn->prepare( "show fields from $table_name where Field = '$key_name'" );
$stm->execute();
$key_type = $stm->fetch()['Type'];
// if there is a primary key
if ($key_name) {
echo "Primary key is $key_name\n";
try {
// if auto_increment was missing there might be a row with key=0 . compute the next available primary key
$sql = "select (ifnull( max($key_name), 0)+1) as next_id from $table_name";
$stm = $conn->prepare( $sql );
echo "$sql\n";
$stm->execute();
$next_id = $stm->fetch()['next_id'];
// give a sane primary key to a row that has key = 0 if it exists
$sql = "update $table_name set $key_name = $next_id where $key_name = 0";
echo "$sql\n";
$stm = $conn->prepare( $sql );
$stm->execute();
// set auto_increment to the primary key
$sql = "alter table $table_name modify column $key_name $key_type auto_increment";
echo "$sql\n";
$stm = $conn->prepare( $sql );
$stm->execute();
} catch (PDOException $e) {
echo "\n\nQuery: $sql\nError:" . $e->getMessage() . "\n\n";
}
} else {
echo "No primary key found for table $table_name.\n";
}
}
echo "\n\nFinished\n";
$conn = null;
In this article we will go through some code that I like to use to make dismissible notices where the dismissal persists between page refreshes in the WordPress administration screens.
Some things to note about dismissible notices
Don’t you just hate how this functionality has still not made it into core? Legend has it that dismissible notices were introduced back in WordPress 4.2, but that only means that when you click the little “x” at the top right, the notice box becomes hidden. The way to enable this is that you add a .is-dismissible class into your notice’s markup:
Upgrade prompts, notices, and alerts should be limited in scope and used sparingly or only on the plugin’s setting page. Any site wide notices or embedded dashboard widgets must be dismissible. Error messages and alerts should include information on how to resolve the situation, and remove themselves when completed.
So for those of us aspiring to be hosted on WordPress.org it’s a necessity, rather than a luxury feature, to be able to let the user dismiss notices persistently.
Requirements analysis
WordPress tradition has it that you store an option in the database. That way you know not to show the same notice again. But this is something that you have to do over and over again, so it’s exactly the kind of thing that you want to include in all your code as a library. You want something that can be easily called from wherever, so the tried and true singleton pattern will do. You need the ability to be able to assign a slug to your notice, so you know how to store it in the options table. But you also want to be able to show the occasional non-dismissible notice. Finally, let’s be nice and clean up after ourselves. The options will be deleted when our plugin is uninstalled.
Let’s do this!
Writing code with class
We need something that can be included from our plugin (or theme). Let’s make a singleton class that can hold arrays of different types of notices (success, info, warn, error):
<?php
// don't load directly
defined( 'ABSPATH' ) || die( '-1' );
if ( ! class_exists( 'MyPlugin_Admin_Notices' ) ) {
class MyPlugin_Admin_Notices {
private static $_instance;
private $admin_notices;
const TYPES = 'error,warning,info,success';
private function __construct() {
$this->admin_notices = new stdClass();
foreach ( explode( ',', self::TYPES ) as $type ) {
$this->admin_notices->{$type} = array();
}
}
public static function get_instance() {
if ( ! ( self::$_instance instanceof self ) ) {
self::$_instance = new self();
}
return self::$_instance;
}
}
}
MyPlugin_Admin_Notices::get_instance();
Nice. This is a useful bucket where we can throw in notices. They will be retrieved for rendering only later, when we will add code to the admin_notices action.
An API for entering notices from our code
For now, let’s add in some methods to our class for populating our notice arrays:
public function error( $message, $dismiss_option = false ) {
$this->notice( 'error', $message, $dismiss_option );
}
public function warning( $message, $dismiss_option = false ) {
$this->notice( 'warning', $message, $dismiss_option );
}
public function success( $message, $dismiss_option = false ) {
$this->notice( 'success', $message, $dismiss_option );
}
public function info( $message, $dismiss_option = false ) {
$this->notice( 'info', $message, $dismiss_option );
}
private function notice( $type, $message, $dismiss_option ) {
$notice = new stdClass();
$notice->message = $message;
$notice->dismiss_option = $dismiss_option;
$this->admin_notices->{$type}[] = $notice;
}
Notice the visibility of the functions. The four public functions that comprise our API all defer to the private function that does the data collection. We’ll let the user enter a message string, and optionally give a slug with the dismiss_option parameter. If set, this will be part of the database option’s slug.
Writing the markup
We have a mechanism for adding notices into our memory, now let’s dump them to the admin area as markup. This will happen on the admin_notices action, so first add this to the constructor:
Note how we show a notice only if the DB does not have a corresponding option named myplugin_dismissed_$dismiss_option. We’ll need a mechanism to set that DB option when the user clicks to dismiss the notice. We will do this from JavaScript, making a call with that option name as a GET parameter, so that we know to set the correct database option.
Notifying the backend from the admin front
When a notice is dismissible, we output a data-dismiss-url attribute in the HTML. We’ll use that from JavaScript to make a call to that URL:
Pretty standard stuff. When a dismissible notice from our plugin is clicked on its .notice-dismiss, get the dismiss_url and call it. I guess I could have used a fancy framework like VanillaJS for this, but I chose plain old jQuery instead :-p
Don’t forget the usual enqueue script shenanigans:
public function action_admin_enqueue_scripts() {
wp_enqueue_script( 'jquery' );
wp_enqueue_script(
'myplugin-notify',
plugins_url( 'assets/scripts/myplugin-notify.js', __FILE__ ),
array( 'jquery' )
);
}
and add this to our constructor so the enqueuing will actually happen:
…and this is the code that will set an option in the database. Note how the name is constructed from the GET parameter in the request URL.
public function action_admin_init() {
$dismiss_option = filter_input( INPUT_GET, 'myplugin_dismiss', FILTER_SANITIZE_STRING );
if ( is_string( $dismiss_option ) ) {
update_option( "myplugin_dismissed_$dismiss_option", true );
wp_die();
}
}
Once the option is set, we can just let WordPress die. No need to return the admin interface to the browser, this is just a background AJAX call.
Cleaning up after ourselves
Unfortunately, even in this day and age, many developers don’t think it’s important to clean up the trash they leave in the poor user’s database. This is even more infuriating when you consider that it rarely takes more than a couple of lines of code. Don’t be that guy. Create an uninstall.php file with the following content.
<?php
if ( defined( 'WP_UNINSTALL_PLUGIN' ) ) {
global $wpdb;
$wpdb->query( 'DELETE FROM wp_options WHERE option_name LIKE "myplugin_dismissed_%";' );
}
We can exploit the fact that we know the common prefix of all the dismissal DB options, and thus we can delete them all in one go, circumventing the delete_option() function altogether:
Expecting the unexpected
If you put together all of the above you already have a nice way to show persistent dismissible admin notices. But why stop there? We can hack away some more and make sure that any runtime errors in our code show up as notices too.
Imagine a clueless user sees your theme not working. Which do you prefer? To have to explain to them how to enable debugging and how to find and send you the logs from the wordpress unix directory on the host? Or do you simply ask them to copy the error on the screen and send it to you via email?
public static function error_handler( $errno, $errstr, $errfile, $errline, $errcontext ) {
if ( ! ( error_reporting() & $errno ) ) {
// This error code is not included in error_reporting
return;
}
$message = "errstr: $errstr, errfile: $errfile, errline: $errline, PHP: " . PHP_VERSION . " OS: " . PHP_OS;
$self = self::get_instance();
switch ($errno) {
case E_USER_ERROR:
$self->error( $message );
break;
case E_USER_WARNING:
$self->warning( $message );
break;
case E_USER_NOTICE:
default:
$self->notice( $message );
break;
}
// write to wp-content/debug.log if logging enabled
error_log( $message );
// Don't execute PHP internal error handler
return true;
}
Notice how this method is static, since we’d like to be able to call it from both dynamic and static contexts. We can now hook it up to PHP’s error reporting like so:
This will pop your error handler from a stack and return to whatever error handling mechanism was there before. Make a habit of surrounding your function bodies with these two lines, and you will know that whatever happens, you’ll at least get a visible user-friendly and developer-friendly error message on the admin screens.
<?php
if ( defined( 'WP_UNINSTALL_PLUGIN' ) ) {
global $wpdb;
$wpdb->query( 'DELETE FROM wp_options WHERE option_name LIKE "/* @echo slugus */_dismissed_%";' );
}
<?php
// don't load directly
defined( 'ABSPATH' ) || die( '-1' );
if ( ! class_exists( 'MyPlugin_Admin_Notices' ) ) {
class MyPlugin_Admin_Notices {
private static $_instance;
private $admin_notices;
const TYPES = 'error,warning,info,success';
private function __construct() {
$this->admin_notices = new stdClass();
foreach ( explode( ',', self::TYPES ) as $type ) {
$this->admin_notices->{$type} = array();
}
add_action( 'admin_init', array( &$this, 'action_admin_init' ) );
add_action( 'admin_notices', array( &$this, 'action_admin_notices' ) );
add_action( 'admin_enqueue_scripts', array( &$this, 'action_admin_enqueue_scripts' ) );
}
public static function get_instance() {
if ( ! ( self::$_instance instanceof self ) ) {
self::$_instance = new self();
}
return self::$_instance;
}
public function action_admin_init() {
$dismiss_option = filter_input( INPUT_GET, 'myplugin_dismiss', FILTER_SANITIZE_STRING );
if ( is_string( $dismiss_option ) ) {
update_option( "myplugin_dismissed_$dismiss_option", true );
wp_die();
}
}
public function action_admin_enqueue_scripts() {
wp_enqueue_script( 'jquery' );
wp_enqueue_script(
'myplugin-notify',
plugins_url( 'assets/scripts/myplugin-notify.js', __FILE__ ),
array( 'jquery' )
);
}
public function action_admin_notices() {
foreach ( explode( ',', self::TYPES ) as $type ) {
foreach ( $this->admin_notices->{$type} as $admin_notice ) {
$dismiss_url = add_query_arg( array(
'myplugin_dismiss' => $admin_notice->dismiss_option
), admin_url() );
if ( ! get_option( "myplugin_dismissed_{$admin_notice->dismiss_option}" ) ) {
?><div
class="notice myplugin-notice notice-<?php echo $type;
if ( $admin_notice->dismiss_option ) {
echo ' is-dismissible" data-dismiss-url="' . esc_url( $dismiss_url );
} ?>">
<h2><?php echo "My Plugin $type"; ?></h2>
<p><?php echo $admin_notice->message; ?></p>
</div><?php
}
}
}
}
public function error( $message, $dismiss_option = false ) {
$this->notice( 'error', $message, $dismiss_option );
}
public function warning( $message, $dismiss_option = false ) {
$this->notice( 'warning', $message, $dismiss_option );
}
public function success( $message, $dismiss_option = false ) {
$this->notice( 'success', $message, $dismiss_option );
}
public function info( $message, $dismiss_option = false ) {
$this->notice( 'info', $message, $dismiss_option );
}
private function notice( $type, $message, $dismiss_option ) {
$notice = new stdClass();
$notice->message = $message;
$notice->dismiss_option = $dismiss_option;
$this->admin_notices->{$type}[] = $notice;
}
public static function error_handler( $errno, $errstr, $errfile, $errline, $errcontext ) {
if ( ! ( error_reporting() & $errno ) ) {
// This error code is not included in error_reporting
return;
}
$message = "errstr: $errstr, errfile: $errfile, errline: $errline, PHP: " . PHP_VERSION . " OS: " . PHP_OS;
$self = self::get_instance();
switch ($errno) {
case E_USER_ERROR:
$self->error( $message );
break;
case E_USER_WARNING:
$self->warning( $message );
break;
case E_USER_NOTICE:
default:
$self->notice( $message );
break;
}
// write to wp-content/debug.log if logging enabled
error_log( $message );
// Don't execute PHP internal error handler
return true;
}
}
}
MyPlugin_Admin_Notices::get_instance();
Thanks for reading
Please comment on what you liked or didn’t like in my code. What would you have done differently? Can you spot any bugs?
In this meta-article I will list eight WordPress checklists and a book that you will want to go through, before you publish a theme or plugin. So before committing to the wordpress.org SVN or uploading to Envato, bookmark this page and start double-checking all the resources listed here!
Actually you’ll probably want to read this before even starting your project; but better late than never! It’s packed with essential info that you should know. If you’ve missed any of the info in this article, go back to your code and fix it. There’s stuff about common practices, coding standards, etc.
This is a list of PHP coding standards that WordPress developers follow, both in core and in themes and plugins. It’s a requirement for submission to wordpress.org but it would be really nice to follow as many of these as possible even if you’re not planning to submit your code there.
Whatever you use, it doesn’t hurt to double check your code one last time. In Eclipse Formatter for instance, there is no way to check for “Yoda” conditions as far as I know, so you’ll want to manually check for those if you’re using it.
Have you checked your PHP code for compliance to the coding standards? Good! Get ready to do it again, this time for your JavaScript files; at least the unminified copies of them. Here’s a project that uses ESLint to help you enforce the standards: https://www.npmjs.com/package/eslint-plugin-wordpress. If you have a lot of JavaScript in your code, it might pay to integrate this into your pre-build checks, but as with PHP, always have one last look using your eyeballs.
If you’re writing a plugin, this is a short list of conditions that your project must meet before you publish to WordPress.org. It has more to do with functionality than standards, and essentially it’s about not being evil with your code.
This is essentially a longer version of the above. A definite must read if you’re publishing to WordPress.org. It’s about licensing, versioning, what you can and can’t do, etc.
If you’re writing a theme that you plan to publish to WordPress.org, check that it at least conforms to all the required items and try to conform to as many recommended items as possible. The write-up for the recommended guidelines is not complete as of the writing of this article, but there’s some very useful guidelines in there.
Again, if you’re writing a theme for WordPress.org, you will also want to check a number of things against the provided Theme Unit Test. It’s probably a good idea to do this even if you’re publishing elsewhere.
This is a list of guidelines to follow before submitting to ThemeForest. There’s a number of things listed that are not allowed, so make sure to check.
When uploading to ThemeForest, you will also want to follow these guidelines. They are mostly about the upload process but also include some information about how to bundle your files.
Professional WordPress: Design and Development
Finally, this is a book, not an actual checklist, but still I recommend that you at least glance through the table of contents. I’ve found this book very helpful. It covers all topics related to WordPress development and it’s very likely that whatever it is you’re trying to do, there might be a better way of doing it. WordPress is a complex system and it’s only getting more complex by the day.
My recommendation is that you go through the table of contents and read any chapter that talks about things you do in your theme or plugin. There are things you might have missed.
Too meta? Perhaps! But no matter what and where you’re publishing, if you want to be professional about it, don’t assume you know everything. At least glance through all of these guidelines.
In this article I’m going to share with you a trick that I use to run wp-cli as the www-data user on my Linux development environment.
wp-cli and file owner issues
I can’t imagine doing any serious WordPress development without wp-cli. It lets you automate the WordPress installation and configuration, lets you install and manage themes and plugins, post articles, and even post file-based media such as images. Whether you run it from grunt, from shell scripts, from inside docker containers, or just from the plain old shell, wp-cli rocks!
One issue I often face is that when I run wp-cli as my default Linux user, naturally all the file operations write files owned by the current user. Sometimes this is an issue, as my web files are normally owned by user www-data (in the www-data group).
In the past that meant that I had to do this a lot, in order to avoid various permission issues:
If you’ve followed the installation instructions, then you probably have wp-cli.phar installed as wp at /usr/local/bin/wp. In any case, you can do
which wp
or
whereis wp
to find its location.
running as www-data
Now on to put a setuid flag on that file and change its owner to that of your web server (usually www-data), right?
Not so fast! The astute Linux aficionado will notice that wp-cli is not a binary, even though it’s placed under a bin dir. Actually it’s a PHP CLI script:
$ head -n 1 `which wp`
#!/usr/bin/env php
$
Here’s what you do instead. First, run visudo with elevated privileges:
sudo visudo
This will let you edit your sudoers file. You want to allow your current user to run your script as www-data. So, add the following line: (here I’m logged in as alex, the local user I use for development)
alex ALL=(www-data) NOPASSWD: /usr/local/bin/wp
Save the file and exit. Now you can do stuff like this:
mkdir /tmp/t
cd /tmp/t
sudo -u www-data wp core download
ls -l
You should see a WordPress installation owned by the www-data user, without ever having to enter a password for www-data (by default there shouldn’t be any password for that user anyway).
Of course, having to type sudo -u www-data wp every time is also tedious. So add this to your ~/.bashrc, or better yet to your ~/.bash_aliases if you have one.
alias wp="sudo -u www-data wp"
That should do it, assuming bash is your shell. For other shells, YMMV.
wp-cli cache permission issue
But now you might notice some warnings of the form:
Warning: copy(/home/alex/.wp-cli/cache/plugin/XXXXXXXX.zip): failed to open stream: Permission denied in phar:///usr/local/bin/wp/php/WP_CLI/FileCache.php on line 164
This just means that the script, which now runs as the www-data user, cannot write to its cache directory, because that directory is owned by you. You can fix this with a simple:
sudo chown -R www-data:www-data ~/.wp-cli/
Now you can use commands such as wp plugin install foo.zip--activate and wp plugin uninstall foo --deactivate in your dev-testing lifecycle without ever worrying about your web server choking on permission issues.