Skip to content

Instantly share code, notes, and snippets.

@jesgs
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesgs/aa78910444f0f9331da0 to your computer and use it in GitHub Desktop.
Save jesgs/aa78910444f0f9331da0 to your computer and use it in GitHub Desktop.
Working with WordPress's Metadata API

Working with WordPress's Metadata API

This tutorial describes how to work with the WordPress Metadata API as described in the tutorial (Working with WordPress's Metadata API) posted on my blog.

/* We start with our table schema: */
CREATE TABLE IF NOT EXISTS `wp_projectmeta` (
`meta_id` bigint(20) NOT NULL AUTO_INCREMENT,
`project_id` bigint(20) NOT NULL,
`meta_key` varchar(255) CHARACTER SET latin1 NOT NULL,
`meta_value` longtext CHARACTER SET latin1 NOT NULL,
PRIMARY KEY (`meta_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
<?php
/**
* 2. Initialization
* This step can vary, depending on if you’re using this for a theme or a plugin.
* You need to add a new table property to $wpdb. For a plugin, you might want to do this on the init hook:
*/
add_action('init', 'my_plugin_init');
function my_plugin_init()
{
global $wpdb;
$wpdb->projectmeta= $wpdb->prefix . 'projectmeta';
}
<?php
$projectmeta = $wpdb->prefix . 'projectmeta';
//...
<?php
add_action('save_post', 'save_custom_data');
function save_custom_data($post_ID)
{
// do nonce checks here
// do autosave/revision checks here
// don't forget to sanitize your meta data before DB insertion.
// depending if the meta_key is unique
if (!add_metadata('project', $post_ID, 'meta_key', 'meta_value', true)) {
update_metadata('project', $post_ID, 'meta_key', 'meta_value');
}
// or if you don't mind an array of meta_keys
add_metadata('project', $post_ID, 'meta_key', 'meta_value');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment