简体   繁体   English

如何处理帖子并在输出之前将其导出为CSV?

[英]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_postsnew 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.

相关问题 导出为 CSV - 如何将我的列名数组用于 output 仅将部分项目用于 CSV? - Export as CSV - how do I use my array of column names to output only some of the items to CSV? 如何在CSV导出中动态设置标题? - How do I dynamically set headers on a CSV export? 如何使用PHP将变量列导出到CSV文件? - How do I export variable columns to a CSV file using PHP? 如何在 json 中通过 query() 和 output 获取 wordpress 帖子? - How to fetch wordpress posts through query() and output them in json? 如何导出WordPress帖子? - How to export WordPress posts? 如何捕获重定向中的所有中间URL并将其导出到CSV文件 - How To Capture All Intermediate URL in a Redirect and Export Them Into a CSV File 我想在导出csv / xls之前计算文件大小(Laravel,Maatwebsite) - I want to calculate filesize before export csv/xls (Laravel, Maatwebsite) 如何在循环输出之前打印for循环的时序? - How do I print the timing of a for loop before the output of the loop? 如何查询与自定义分类相关的所有帖子,然后查询 output 这些页面标题? - How do I query all posts associated with a custom taxonomy and then output those pages titles? 如何在CSV导出之前将我的数据库ID号转换为文本? - How to convert my database ID number to text before CSV export?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM