As part of my hacking on WordPrss, I got to a point where I wanted to let folks import and export OPML files.
Exporting a file from a WordPress plugin doesn’t seem to be very well documented. I found an older article about it – here’s my take.
Provide a link to the file export
<a href="<?echo site_url() ?>?export_opml=<?php echo wp_get_current_user()->ID ?>">Export OPML</a> |
Export the data
This file isn’t getting included in through the normal wordpress mechanisms, so it has to do some more work than the rest of your plugin does. If you want to use the $wpdb or other handy wordpress items, you have to include those in.
I was about to hack up a way to include wp-config.php or wp-load.php when I ran across the simply named Don’t Include WP-Load, Please. He recommends a clever way to handle it all within wordpress, which I quite like. See below.
//in the main plugin file | |
//We want to make a query variable called export_opml | |
add_filter('query_vars','plugin_add_trigger'); | |
function plugin_add_trigger($vars) { | |
$vars[] = 'export_opml'; | |
return $vars; | |
} | |
//and if we see that query variable, we include the file we want to send | |
add_action('template_redirect', 'plugin_trigger_check'); | |
function plugin_trigger_check() { | |
if(intval(get_query_var('export_opml')) == wp_get_current_user()->ID) { | |
require_once 'export_opml.php'; | |
//exit, because we don't want to send any of the rest of WP - no menus, posts, etc. | |
exit; | |
} | |
} |
Now you can build out your export file – in this case export_opml.php – knowing that all of the WordPress utilities are there for you to use.
<?php | |
// Set the headers so the file downloads | |
header('Content-type: application/xml+opml'); | |
header('Content-Disposition: attachment; filename="Wordprss-OPML-Export.xml"'); | |
//oh PHP. Why you gotta be so difficult about escaping things? | |
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?".">"; | |
?> | |
<opml version="1.0" > | |
<head> | |
<dateCreated> | |
<?php echo date("r", time())?> | |
</dateCreated> | |
<title> | |
WordpRSS OPML Feed Export | |
</title> | |
</head> | |
<body> | |
<?php | |
//this file requires $wpdb and the like. | |
require_once 'backend.php'; | |
// this should take in a param. | |
// the param should be a userid. | |
// if the userid == current user, we export everything but private | |
// otherwise, just export the public stuff. | |
$feeds = WprssFeeds::get(); | |
foreach($feeds as $feed){ | |
?> | |
<outline text="<?php echo $feed->feed_name?>" title="<?php echo $feed->feed_name?>" type="rss" xmlUrl="<?php echo $feed->feed_url?>" htmlUrl="<?php echo $feed->site_url?>"/> | |
<?php | |
} | |
?> | |
</body> | |
</opml> | |
<?php | |
exit; | |
?> | |