Skip to content

Instantly share code, notes, and snippets.

@mattbeck
Last active January 30, 2018 07:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattbeck/e4cd732bbf94ff2c865f to your computer and use it in GitHub Desktop.
Save mattbeck/e4cd732bbf94ff2c865f to your computer and use it in GitHub Desktop.
Sample WordPress Data Import Plugin
<?php
/**
* Plugin Name: Run-Once Data Importer
* Description: This plugin will add custom field data to a predefined set of posts
* Version: 1.0
* Author: mattbeck
*/
register_activation_hook( __FILE__, 'runonce_data_import' );
function runonce_data_import() {
$meta_key = 'key-of-custom-field';
// Grab data you want to add to your custom field, prepare a key/val array of post IDs and data to add.
// The real code would depend on the original data source and how you intend to compare WordPress Post IDs to the new data.
// Could be built in a loop, pulled from a CSV, whatever.
$import_data[0]['post_id'] = 1;
$import_data[0]['content'] = '<div class="someclass"><p>Some more stuff in here</p></div>';
$import_data[1]['post_id'] = 2;
$import_data[1]['content'] = '<div class="someclass"><p>Some other different stuff in here</p></div>';
foreach($import_data as $data){
add_post_meta($data['post_id'], $meta_key, $data['content'], true);
}
}
?>
@ChrisBinge
Copy link

Some more stuff in here

'; // $import_data[1]['post_id'] = 2; // $import_data[1]['content'] = '

Some other different stuff in here

'; foreach($import_data as $data){ add_post_meta($data['post_title'], $meta_key, $data['content'], true); } } ``` ?>

So I added in my data, and I'd like to filter through by post_title. I activated the plugin as pasted above, and no luck. Is there something I missed?

@mattbeck
Copy link
Author

You can't swap in post_title like that, you need the post_id

If you have only the title you'd need to run a query to get the ID first.

http://codex.wordpress.org/Function_Reference/add_post_meta

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment