正在尝试添加管理文件上载表单插件

时间:2020-05-16 作者:Jesse Aldridge

我正试图通过插件从我的管理页面创建一个上传表单。

我已经从一些来源拼凑了一些代码,包括这一个:https://www.htmlgoodies.com/beyond/cms/create-a-file-uploader-in-wordpress.html

当我提交表单时,我得到一个500错误,不知道为什么或者如何进一步调试。

这是不是文件上传表单的错误方式?

我的插件有两个文件:

wp-content/plugins/test_upload/test_upload.php

<?php
   /*
   Plugin Name: test_upload
   Version: 1.0
   */

  add_action(\'admin_menu\', \'test_plugin_setup_menu\');

  function test_plugin_setup_menu(){
      add_menu_page( 
          \'Test Upload\', \'Test Upload\', \'manage_options\', \'test-upload\', \'upload_page\' 
      );
  }

  function upload_page(){
      ?>
      <h1>Test Upload Form</h1>  

      <form id="upload_form" action="/wp-content/plugins/test_upload/main.php" enctype="multipart/form-data" method="post" target="messages">
        <p><input name="upload" id="upload" type="file" accept="text/csv" /></p>
        <p><input id="btnSubmit" type="submit" value="Upload selected csv file" /></p>
        <iframe name="messages" id="messages"></iframe>
      </form>
  <?php
  }

wp-content/plugins/test_upload/main.php

<?php
//provides access to WP environment
require_once($_SERVER[\'DOCUMENT_ROOT\'] . \'/wp-load.php\');  
 
  /* import
  you get the following information for each file:
  $_FILES[\'field_name\'][\'name\']
  $_FILES[\'field_name\'][\'size\']
  $_FILES[\'field_name\'][\'type\']
  $_FILES[\'field_name\'][\'tmp_name\']
 */
  
if($_FILES[\'upload\'][\'name\']) {
  if(!$_FILES[\'upload\'][\'error\']) {
    //validate the file
    $new_file_name = strtolower($_FILES[\'upload\'][\'tmp_name\']);
    //can\'t be larger than 300 KB 
    if($_FILES[\'upload\'][\'size\'] > (300000)) {
      //wp_die generates a visually appealing message element
      wp_die(\'Your file size is to large.\');
    }
    else {
      //the file has passed the test
      //These files need to be included as dependencies when on the front end.
      require_once( ABSPATH . \'wp-admin/includes/image.php\' );
      require_once( ABSPATH . \'wp-admin/includes/file.php\' );
      require_once( ABSPATH . \'wp-admin/includes/media.php\' );
       
      // Let WordPress handle the upload.
      // Remember, \'upload\' is the name of our file input in our form above.
      $file_id = media_handle_upload( \'upload\', 0 );
 
      if ( is_wp_error( $file_id ) ) {
         wp_die(\'Error loading file!\');
      } else {
        wp_die(\'Your menu was successfully imported.\');
      }
    }
  }
  else {
    //set that to be the returned message
    wp_die(\'Error: \'.$_FILES[\'upload\'][\'error\']);
  }
} 
?>

1 个回复
SO网友:Jesse Aldridge

原来代码是正确的,问题是我复制/粘贴的教程站点使用了奇怪的非标准空格字符,而不是普通空格。我用“普通空间”替换了“假空间”,现在一切都正常了。

为了调试这个,我需要查看Apache错误日志,而不是WordPress错误日志。这最终引导我来到这里:https://stackoverflow.com/questions/11493751/unexpected-t-string-in-if-clause-with-spaces

相关推荐

如何在wp-admin的Pages部分下列出新添加的ftp网页?

我通过文件管理器上传了一个自定义页面(html、css和一些脚本),并希望客户能够通过管理区域中的管理“页面”菜单访问此页面。可通过访问该页面www.site.com/{my_page} 但管理区不承认Pages.我应该如何把它放在管理区的页面部分?