Extra "uploads" added in path

时间:2018-06-21 作者:Phantasmix

虽然这与高级自定义字段相关,但此函数使用所有本机WP特性,因此我认为在这里询问这一点是合适的。路径中的额外“/上传/”来自何处?

在后端,我看到了上传文件的正确链接(domain.com/wp-content/member-files/name.pdf),但在前端,URL在路径(domain.com/wp-content/uploads/member-files/name.pdf)中显示了额外的“/uploads/”,当然为文件生成了404。

// file upload to custom location

add_filter( \'acf/upload_prefilter/name=protected_files\',
\'protected_upload_prefilter\' );
add_filter( \'acf/prepare_field/name=protected_files\', 
\'protected_files_field_display\' );
function protected_upload_prefilter( $errors ) {

add_filter( \'upload_dir\', \'protected_upload_directory\' );

return $errors;

}

function protected_upload_directory( $param ) {

  $folder = \'/member-files\';

  $param[\'path\'] = WP_CONTENT_DIR . $folder;
  $param[\'url\'] = WP_CONTENT_URL . $folder;
  $param[\'subdir\'] = $folder;
  $param[\'basedir\'] = WP_CONTENT_DIR;
  $param[\'baseurl\'] = WP_CONTENT_URL;

  return $param;

}

// front-end display

function protected_files_field_display( $field ) {

  // update paths accordingly before displaying link to file
  add_filter( \'upload_dir\', \'protected_upload_directory\' );

  return $field;

}
与转发器字段一起使用,输出文件链接如下:

       // check if the repeater field has rows of data
        if( have_rows(\'protected_uploads\') ):

            // loop through the rows of data
            while ( have_rows(\'protected_uploads\') ) : the_row(); 
            $file_url = get_sub_field(\'protected_files\'); 
        ?>

           <p><a href="<?php echo $file_url; ?>">
                <?php the_sub_field(\'date\'); ?> Appendix</a>
           </p>

* EDIT *

删除此行对任何内容都没有任何影响:

$param[\'subdir\'] = $folder;

* EDIT 2 *

我尝试将$param更改为WP\\u PLUGIN\\u DIR和WP\\u PLUGIN\\u URL。同样,这将在后端显示正确的URL(现在改为/plugins/directory而不是/uploads/),但奇怪的是,在前端,所有文件链接都指向域。com/wp内容/上传/文件。pdf格式

确认它是由upload_dir 第二部分中的位。所以,我缩小了范围。应该用什么替换它来获取实际的上载目录?在这一点上,我甚至可以硬编码上传文件的位置。

1 个回复
最合适的回答,由SO网友:Phantasmix 整理而成

以完全不同的方式解决。谷歌搜索了这个,所以技术上不是我自己的答案,但确实做到了:

// ACF upload prefilter
function gist_acf_upload_dir_prefilter($errors, $file, $field) {

    // This filter changes directory just for item being uploaded
    add_filter(\'upload_dir\', \'gist_acf_upload_dir\');
}

// ACF hook, set to field key of your file upload field
add_filter(\'acf/upload_prefilter/key=field_5b2b0326ea0e1\', \'gist_acf_upload_dir_prefilter\');

// Custom upload directory function, trigger by prefilter
function gist_acf_upload_dir($param) {

    // Set to whatever directory you want the ACF file field to upload to
    $custom_dir = \'/uploads/member-files\';
    $param[\'path\'] = WP_CONTENT_DIR . $custom_dir;
    $param[\'url\'] = WP_CONTENT_URL . $custom_dir;
    return $param;
}

结束