我有这个包含附件 id 的元字段
例如
get_post_meta(get_the_ID(), 'test_file', true)
我需要下载此文件并使用此代码计算元字段中的下载次数。
$postID = get_the_ID;
$number_downlode = get_post_meta($postID, 'downlode_registration', true);
$number_downlode++;
update_post_meta($postID, 'downlode_registration', $number_downlode);
但我不知道该怎么做。
我尝试使用 onclick 命令和 ajax
<?php setPostViews(get_the_ID()); ?>
<?php $GET11 = wp_get_attachment_url ( get_post_meta(get_the_ID(), 'test_file', true) );?>
<a href="<?php echo $GET11 ?>" download onclick="isEmail()">Click Me</a>
<script type="text/javascript">
function isEmail() {
$(document).ready(function(){
$.ajax({
type: 'POST',
url: 'script.php',
success: function(data) {
document.write("data");
}
});
}); }
</script>
脚本.php
$postID = get_the_ID;
$number_downlode = get_post_meta($postID, 'downlode_registration', true);
$number_downlode++;
update_post_meta($postID, 'downlode_registration', $number_downlode);
但是script.php文件看不到wordpress
我还尝试使用 POST 方法下载文件
<?php
if ( get_post_meta(get_the_ID(), 'test_file', true) ) :
$GET11 = get_post_meta(get_the_ID(), 'test_file', true) ;
?>
<form method="POST">
<input type="submit" value="downlode" name="test_downlode">
</form>
<?php if ($_POST['test_downlode']){
$number_downlode = get_post_meta($postID, 'downlode_registration', true);
$number_downlode++;
update_post_meta($postID, 'downlode_registration', $number_downlode);
$file = ($GET11);
if (file_exists($file)) {
if (ob_get_level()) {
ob_end_clean();}
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;}}
endif; ?>
但是无论我尝试了多少,页面都看不到 $file 变量中的文件
我需要通过元字段完成计算,因为稍后我将通过 get_posts() 过滤页面。
插件在这里不起作用。
要解决这个问题,你需要做两件事:拦截点击链接并将文件提供给使用 php.ini 的真实用户。
当您单击指向不存在的页面的虚拟链接时会发生什么?WordPress 初始化内核并尝试发出 404 页面,此时您需要干预您的函数,更新下载计数器并给出真实文件。以下是此类功能的代码。
该函数
rewrite_download_link()在 event 上触发init,并检查 url 是否以 开头$link_base,例如,它可能是/downloads/. 任何视图链接都被http://site.org/downloads/cool.jpg认为是虚拟的,需要进行处理,更新下载计数器,计算文件的真实 url,并调用函数将真实文件返回给用户。该函数的代码如下所示。
该函数
download_file()使接收到的文件相对链接并计算文件的路径,然后使用 php.ini 将其返回。因此,用户无法找到真实文件的位置并直接下载。包含上述方法的完整类代码可以在我们的 GitHub 上找到。