Hook for URL Request

时间:2012-10-03 作者:User

我想让XML文件可以下载,而不是让浏览器内联显示它们。

我知道我可以使用Content-Disposition: attachment HTTP头(当然,欢迎使用更好的解决方案!)。当用户尝试下载XML文件时,我想在所有HTTP响应中添加此标头。

I can use the following PHP code:

header(\'Content-Disposition: attachment; filename="the_filename.xml"\');
问题是:何时可以调用此指令?我应该用什么钩子,怎么用?

3 个回复
SO网友:EAMann

实际上,我的建议是做一些不同的事情。您可以向WordPress添加自定义重写端点,以专门处理这些文件。

例如,URLhttp://site.com/download-xml/the_filename 将自动下载指定的文件作为附件。

首先,您需要添加一个自定义重写端点来进行设置:

function add_endpoint() {
    add_rewrite_endpoint( \'download-xml\', EP_ALL );
}
add_action( \'init\', \'add_endpoint\' );
这还方便地添加了一个查询变量,以便我们可以检查该端点是否在标准模板重定向期间使用。

function download_redirect() {
    global $wp_query;

    // If this isn\'t the right kind of request, bail.
    if ( ! isset( $wp_query->query_vars[\'download-xml\'] ) || empty( $wp_query->query_vars[\'download-xml\'] ) )
        return;

    // Download the file.

    exit();
}
add_action( \'template_redirect\', \'download_redirect\' );
在上面的函数中,您可以执行下载文件所需的任何操作。从加载/wp-content/uploads 目录作为流,设置文件头(内容配置设置为“附件”),根据数据库中的内容动态生成内容,无论您想要什么。

只要确保exit() 最后调用,否则WordPress将尝试执行其常规模板重定向调用,稍后您将收到一些丑陋的“headers ready sent”错误。

SO网友:Michael Ecklund

你需要看看Plugin API/Action Reference/send headers

Example:

add_action( \'send_headers\', \'add_header_xua\' );
function add_header_xua() {
     header( \'X-UA-Compatible: IE=edge,chrome=1\' );
}

SO网友:Sumit Parkash

我想你可以用parse_request 行动挂钩parse_request

add_action(\'parse_request\', \'handleDownload\', 10, 1);

结束

相关推荐

WXR XML导入正在剥离我需要保留的php标记

当我导入WXR XML 文件wp\\u insert\\u post(或其他函数)似乎正在应用过滤器来去除我需要保留在内容中的php标记。我搜索了各种wp include php文件以查找:wp_insert_post, sanitize_post, wp_strip_all_tags但我不知道要编辑哪些文件,以及要进行哪些编辑以避免剥离php标记。非常感谢您的建议和帮助。提前谢谢。