databasewordpresspluginspost-meta

Post meta vs separate database tables


there is one big question in my mind why do developer plugin use post meta for saving data on database ? why don't use separate tables ? i know that if you lot of data you will save data on seprate tables and data related post better save on wp_postmeta What other reasons are there to store or not store data in post meta?


Solution

  • Ahh, why indeed? WordPress's meta tables can be slow to query and confusing to use. The string-only meta values present real problems when you use them to store numbers or datestamps, for just one example of how confusing they are.

    They do permit developers to extend WordPress's data model to handle many imaginable applications, without extra tables (or worse, custom columns added to the users or posts tables). If it weren't for this extensibility I suspect nobody would have heard of WordPress in 2022.

    But here's the thing. Most people who own sites or develop plugins (or themes) for the WordPress.org software ecosystem aren't proficient with designing or developing for SQL tables. It's easier for many to rely on the meta table instead.

    Some plugins (Yoast, Relevanssi, WooCommerce for example) have their own tables, and your plugin can have them too if you need them.

    If you will publish a plugin like that you must include code to create your tables when your user first activate your plugin, and drop them when she deletes your plugin. And you need to test those cases carefully, lest you leave junk behind in your users' databases.

    You must be careful to use the right $wpdb->prefix for your table names (or your plugin will collapse in a heap of digital rubble on multisite installations). To avoid SQL injection attacks you must use $wpdb->prepare(). And there are other things to keep in mind. Study up on the $wpdb class.