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.
Last active
August 29, 2015 14:18
-
-
Save jesgs/aa78910444f0f9331da0 to your computer and use it in GitHub Desktop.
Working with WordPress's Metadata API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$projectmeta = $wpdb->prefix . 'projectmeta'; | |
//... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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