[英]How do I process posts and export them as CSV before output?
I am trying to export as CSV a list of custom type posts directly from Wordpress' dashboard (edit.php). 我正在尝试直接从Wordpress的信息中心(edit.php)将CSV类型的自定义类型帖子列表导出。 This is my code so far:
到目前为止,这是我的代码:
add_filter('pre_get_posts', 'yri_export_csv');
function yri_export_csv($query) {
if(is_admin() && $query->get('post_type') == 'kohde' && isset($_GET['export_csv'])) {
$kunta = $query->get('kunta');
$osasto = $query->get('osasto');
$time = time();
$args = $query->query;
$posts = get_posts($args);
header('Content-type: application/csv');
header("Content-Disposition: attachment; filename=kohteet_{$kunta}_{$osasto}_{$time}.csv");
foreach ($posts as $post) {
// Do CSV stuff here
}
die();
}
}
The problem is that when I query the posts using get_posts
or new WP_Query
Wordpress for some reason redirects me to the frontend, to a 404 page. 问题是当我出于某种原因使用
get_posts
或new WP_Query
Wordpress查询帖子时,会将我重定向到前端,即404页面。 Why does it do that? 为什么这样做呢?
This solved it: 这解决了它:
...
if(is_main_query() && is_admin() && $query->get('post_type') == 'kohde' && isset($_GET['export_csv'])) {
...
I'm not exactly sure why. 我不确定为什么。 There seems to be some kind of redirecting mechanic in Wordpress here and I don't exactly understand how it works.
这里似乎在Wordpress中有某种重定向机制,但我不完全了解它是如何工作的。 However, testing for main query,
is_main_query()
, was the missing piece. 但是,缺少对主查询
is_main_query()
测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.