Blog / Build with AI /

Prompting for code: how to ask AI for something that actually runs

You ask a chatbot for a bit of code. It answers in seconds, looks confident and the formatting is lovely. You paste it in, and it fails with an error you do not understand.

This is the most common experience of using AI for code, and it is usually not the AI’s fault alone. The question was too vague, so the answer was a guess. The good news is that asking better is a skill you can learn in an afternoon. This guide covers a method, a template and a worked example.

I am writing in January 2023, when ChatGPT is only a few weeks old, so treat the details as a snapshot of an early tool. The principles should hold up longer than the tool does.

The core idea

An AI model does not know your project. It does not know your computer, your WordPress version or what you meant. It fills the gaps with the most likely thing, which is often wrong for you.

So the whole craft of prompting for code comes down to one job: remove the gaps. Every detail you leave out is one the model will invent.

The six-part prompt

I use a simple structure. You do not need every part every time, but the more you include, the better the result.

  1. Context: where will this code run? Which language, version, platform and tools?
  2. Goal: what should it do, in one or two plain sentences?
  3. Input and output: what goes in, and what should come out? Give an example.
  4. Constraints: what must it avoid or respect? For example, no extra libraries, must be safe to test, must not change files.
  5. Your level: tell it if you are a beginner and want comments and explanations.
  6. Format: do you want the full file, only the changed lines or an explanation first?

A template

Context: I’m using [language and version] on [Windows/Mac/Linux / WordPress version / platform].
Goal: Write a script that [what it does].
Input: [what you give it, with an example].
Output: [what you want back, with an example].
Constraints: [libraries allowed, safety rules, things to avoid].
About me: I’m a [beginner/intermediate]. Please comment each step and explain how to run it.

Fill in the brackets and the answers get noticeably better.

A worked example

Say you want to check a list of web addresses and see which ones respond properly. Here is a weak prompt:

Write code to check URLs.

The model has to guess the language, where the URLs live, what “check” means and how you want the results. You will get something, but probably not what you need.

Now a better one:

I’m a beginner using Python 3 on Windows. I have a CSV file called urls.csv with a column called “url”. Write a script that reads each URL and prints the URL and its HTTP status code. If a request fails, print the URL and the word “error” instead of crashing. Use the requests library, set a 10-second timeout, and do not follow redirects, so I can see 301s. Comment each step and tell me how to install anything I need.

A good answer would look something like this:

import csv
import requests

with open("urls.csv", newline="") as f:
    for row in csv.DictReader(f):
        url = row["url"]
        try:
            r = requests.get(url, timeout=10, allow_redirects=False)
            print(url, r.status_code)
        except requests.RequestException as e:
            print(url, "error", e)

You would also be told to run pip install requests first. Look at how every instruction in the prompt turned into a visible line in the code: the CSV column, the timeout, the redirect setting and the error handling. That is the pattern. Detail in, detail out.

Techniques that make a real difference

Give an example of the input and output

A small sample is worth a paragraph of explanation. Paste three rows of your data and write what you expect to come out. The model then copies the shape of your example.

Ask for a plan before code

For anything bigger than a few lines, try:

Before writing code, list the steps you would take and any assumptions you are making. Wait for me to confirm.

You will catch wrong assumptions early, when they are cheap to fix.

Start small, then grow

Do not ask for a whole application. Ask for one function, test it, then ask for the next piece. Small pieces are easier to check and easier to fix.

Paste the real error message

When something fails, copy the complete error text and paste it back with the code that caused it. Say what you expected to happen. The model is quite good at reading errors, and you save time by giving it the exact words.

Ask it to explain

If you do not understand a line, ask. “Explain this line by line as if I am new to Python.” If you cannot explain code, you should not run it on something important.

Name the version

Software changes. A WordPress function that existed in one version may be deprecated in another. A model trained on older data may suggest outdated methods, because its knowledge stops in 2021. Mention your version, and be ready to check the official documentation.

Tell it what not to do

Constraints are powerful. “Do not use any external libraries.” “Do not delete anything.” “Do not change my existing function names.” Boundaries produce safer code.

A second worked example: spreadsheet formulas

Code is not only scripts. If you work in a spreadsheet, the same method applies to formulas. A weak prompt:

Formula to clean my data.

A better one:

I’m using Google Sheets. Column A has page titles with extra spaces at the start and end, and some are in capital letters. In column B, I want the same title trimmed and in lower case. Give me the formula for cell B2 that I can drag down, and explain each part.

The answer should be something like =LOWER(TRIM(A2)), along with an explanation that TRIM removes the extra spaces and LOWER changes the case. Because you named the tool, the columns and the result you wanted, the model had no room to guess. Because you asked for an explanation, you learn something each time.

Common prompting mistakes

  • Asking for the finished product in one go. Break it into pieces.
  • Leaving out the platform. A snippet for WordPress is different from one for a plain PHP page.
  • Changing three things at once. When it breaks, you will not know why.
  • Pasting only the error, not the code. The model cannot see the file.
  • Skipping the question “what could go wrong?” Ask it. The answers are often useful.
  • Treating the chat as memory. Long conversations lose track of early details, so restate the key facts when you return to a task.

When the code does not run

It will happen. Here is a routine.

  1. Read the error. The last line often says what went wrong.
  2. Check the obvious. The file name, the folder, a missing library or a typo in a column name.
  3. Paste the full error and the code back into the chat, with a note of what you expected.
  4. Ask for one fix at a time. Do not accept a rewrite of everything unless the structure was wrong.
  5. Try a simpler version. Strip the task back to the smallest piece that fails.
  6. Search the error text in a search engine or the official documentation if the model keeps going in circles.

If it goes round the same wrong answer three times, start a new conversation with a cleaner prompt. Long chats can drift.

What to check before trusting any result

The short version of the review you should always do:

  • Does the code do anything beyond what you asked?
  • Does it delete, overwrite or send data anywhere?
  • Do the functions and libraries it uses actually exist?
  • Have you tested it on a copy of your data?
  • Can you explain what each part does?

Never paste anything into a live website or production system without a backup and a test.

Prompting for WordPress

A few extras if you use the tool for WordPress snippets:

  • Say that it is for WordPress, give the version, and say whether it will go into a plugin or the theme’s functions file.
  • Ask for a code that uses the standard WordPress hooks and functions, not custom workarounds.
  • Ask it to sanitise input and escape output, because security is easy to forget.
  • Ask where the code should go and how to remove it again.

Then test on a staging site first.

Common myths

  • “A better model fixes bad prompts.” Models improve, but missing context stays missing.
  • “Longer prompts are always better.” Clear beats long. Include what is relevant.
  • “If it ran without errors, it is correct.” Code can run and still do the wrong thing.
  • “You need to know the right magic words.” You need to be specific and honest about what you want.
  • “AI makes learning to code pointless.” It makes understanding code more valuable, because you must judge what it gives you.

Keeping a prompt library

Once a prompt works, keep it. A plain text file with your best prompts, each with a line on what it was for and what you had to fix afterwards, becomes a small toolkit. Next time you need a similar script, you start from a tested prompt instead of a blank page. Over a few months this saves more time than any single clever trick, and it forces you to notice which details made the difference.

Add the failures too. A note such as “forgot to say the file was UTF-8, got garbled characters” is exactly the kind of detail you will forget and meet again.

Using AI to review code, not just write it

The same skills work in reverse. Paste in code you have been given, or code from a tutorial, and ask:

Explain what this code does in plain English, step by step. Then list anything in it that could delete data, send data elsewhere or cause a security problem.

You still verify the answer, because the model can miss things or invent concerns. But as a second pair of eyes before you run something unfamiliar, it is a cheap and useful habit.

A short checklist

Before you press enter:

  • Did I say what language, version and platform?
  • Did I say what goes in and what should come out?
  • Did I include an example?
  • Did I list what it must not do?
  • Did I say my level and ask for comments?
  • Do I know how I will test it safely?

Key takeaways

  • Vague prompts get guesses. Specific prompts get working code.
  • Use six parts: context, goal, input and output, constraints, level and format.
  • Include examples, work in small pieces and paste real errors back.
  • Read and test everything, on a copy, before it touches anything live.
  • Understanding the code is still your job.

I have given you a template. What is the first small job you will use it on?