It doesn’t. WordPress doesn’t use foreign keys to link tables together that way. There are also lots and lots of other reasons to declare keys and primary keys in a table that have nothing to do with this type of linkage/referencing. For example telling MySQL/MariaDB the ID column is a primary key give critical clues and hints to how it should store and index that table for performance.
For a custom plugin I want to recreate the terms, taxonomy and relationship tables from wordpress in my own tables But WordPress do not use FOREIGN KEY, only ‘UNIQUE KEY’ and ‘KEY’ in sql syntaxe.
I do not see why FOREIGN KEY
is needed for this, or why you need to create new tables.
Any “object” can have a taxonomy, not just posts. User taxonomies are a thing for example. The requirement though is that all objects in a taxonomy are the same type, so you can’t mix users and posts as it has no way of knowing if the ID 5 is for the user 5 or the post 5.
So register a taxonomy then pass it the IDs of your custom things, not post IDs. Don’t create your own tables, this will add an enormous amount of technical debt and additional work, while preventing compatibility with most of the tools available.
How Does WP query for posts terms meta etc together?
Using SQL queries and JOIN statements constructed in PHP.
A post meta table entry has a column containing the ID of the post. When WordPress wants to fetch all meta for a post it fetches those rows that have the matching ID using a SELECT
statement in a follow up query, or a JOIN
. WP_Query
, WP_Term_Query
, WP_User_Query
etc are the relevant classes.
Keep in mind that WordPress does not use or implement an ORM database system, and predates many of the big PHP ORM database libraries such as Doctrine. Objects such as WP_Post
are just containers for data and can’t be used to delete/update/create.
You also shouldn’t be constructing your own database tables in WordPress routinely. Custom database tables are possible but there is almost no UI support for them, and no API support for accessing them beyond raw SQL.
For example when querying it might use JOIN
to select only the post meta with an ID that matches the post, but this is all done in PHP in the application layer. The database is unaware that the post ID 5 in the post meta tables post ID column refers to the ID of a row in the posts table.
Note that the columns that store these IDs are just that, columns that store a number that represents an ID. There is no magic to tie it to a row in another table automatically, no links. You can create rows in the post meta table for posts that don’t exist for example, nothing on the database side enforces that it must have the ID of a post that exists.
This also means if you delete a post with raw SQL it won’t delete the term associations or post meta, those are all done in PHP triggering separate DB queries.