首页 > 解决方案 > 如何修复 wordpress admin-ajax 中的 404 错误?

问题描述

我正在尝试自定义提交高级自定义字段专业数据,其中包括使用 ajax 的图像字段,而不使用 acf 提供的本机提交。

这似乎是重新发明轮子,但这是它适用于我的用例的唯一方法,它是一个多步骤形式。开箱即用的 acf 不为此提供功能。

我目前收到POST https://dev.energypages.com/wp-admin/admin-ajax.php 400 ()错误,我不知道为什么,如果有一双新的眼睛可以看看我的代码,我将不胜感激看看他们是否能找到我找不到的任何问题。

此外,我未能成功获取图像数据和字符串数据。

Javascript:

$(".nexttwo").on('click', function() {
  resetErrors();

  current_fs = $(this).parent();
  next_fs = $(this).parent().next();
  var comid = getUrlParameter('cid');

  var companydata = new FormData(this);
  companydata.append("comdata", "company_info");
  companydata.append("cid", comid);

  $.ajax({
    url: ajaxurl,
    processData: false,
    contentType: false,
    dataType: 'json',
    method: 'post',
    data: companydata,
    success: function(data) {
      console.log(JSON.stringify(data));
      for (var i = 0; i < data.length; i++) {
        var status = data[i].code;
        var field = data[i].field;
        var message = data[i].msg;
        //var comid = data[i].cid;

        if (status == "200") {
          //successful validation
          if (animating) return false;
          animating = true;

          //activate next step on progressbar using the index of next_fs
          $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");

          //show the next fieldset
          next_fs.show();
          //hide the current fieldset with style
          current_fs.animate({
            opacity: 0
          }, {
            step: function(now, mx) {
              //as the opacity of current_fs reduces to 0 - stored in "now"
              //1. scale current_fs down to 80%
              scale = 1 - (1 - now) * 0.2;
              //2. bring next_fs from the right(50%)
              left = (now * 50) + "%";
              //3. increase opacity of next_fs to 1 as it moves in
              opacity = 1 - now;
              current_fs.css({
                'transform': 'scale(' + scale + ')'
              });
              next_fs.css({
                'left': left,
                'opacity': opacity
              });
            },
            duration: 800,
            complete: function() {
              current_fs.hide();
              animating = false;
            },
            //this comes from the custom easing plugin
            easing: 'easeInOutBack'
          });
        } else {
          var msg = '<label class="acf-notice -error acf-error-message error" for="' + field + '">' + message + '</label>';
          $('input[name="' + field + '"], select[name="' + field + '"]').addClass('acf-error').before(msg);
        }
      }
    }
  });
});

PHP:

function company_info($post_id){
    if( isset($_POST['cid']) )
    $post_id = $_POST['cid'];

    // These files need to be included as dependencies when on the front end.
    require_once( ABSPATH . 'wp-load.php');

    //Log form data
    $file_path = plugin_dir_path( __FILE__ );
    $filename = $file_path.'companyinfo.txt';

    //Get form data
    $data = $_POST['comdata'];

    file_put_contents($filename, $data);

    $formdata = array();
    parse_str($data, $formdata);


    //Prepare company info
    $cname = strtolower($formdata['acf']['field_5bef0f8c743f6']);
    $clogo = $formdata['acf']['field_5bef0fac743f7'];
    $cwebsite = $formdata['acf']['field_5bef100b743f8'];
    $cphone = $formdata['acf']['field_5bef1032743f9'];
    $caddress = $formdata['acf']['field_5bef108a743fa'];

    $errorMSG = [];

    /* COMPANY NAME */
    if ( empty($cname) ) {
        $errorMSG[] = array('code' => 404, 'field' => 'acf[field_5bef0f8c743f6]', 'msg' => 'Company name is required');
    }

    /* COMPANY LOGO */
    if ( empty($clogo) ) {
        $errorMSG[] = array('code' => 404, 'field' => 'acf[field_5bef0fac743f7]', 'msg' => 'Company logo is required');
    }

    $success = [];

    if( empty($errorMSG) ){
        $uploadedfile = $_FILES['acf[field_5bef0fac743f7]'];
        $upload_name = $_FILES['acf[field_5bef0fac743f7]']['name'];
        $uploads = wp_upload_dir();
        $filepath = $uploads['path']."/$upload_name";

        if ( ! function_exists( 'wp_handle_upload' ) ) {
            require_once( ABSPATH . 'wp-admin/includes/file.php' );
        }
        require_once( ABSPATH . 'wp-admin/includes/image.php' );
        require_once( ABSPATH . 'wp-admin/includes/media.php' );

        $upload_overrides = array( 'test_form' => false );
        $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
        if ( $movefile && !isset( $movefile['error'] )  ) {

            $file = $movefile['file'];
            $url = $movefile['url'];
            $type = $movefile['type'];

            $attachment = array(
                'post_mime_type' => $type ,
                'post_title' => $upload_name,
                'post_content' => 'File '.$upload_name,
                'post_status' => 'inherit'
                );

            $attach_id = wp_insert_attachment( $attachment, $file, 0);
            $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
            wp_update_attachment_metadata( $attach_id, $attach_data );

        }
        // Let WordPress handle the upload.
        //$img_id = media_handle_upload( 'acf[field_5bef0fac743f7]', 0 );

        file_put_contents($filename, $attach_id);

        update_field('field_5bef0fac743f7', $attach_id, $post_id);


        update_field('field_5bef0f8c743f6', $cname, $post_id);
        update_field('field_5bef100b743f8', $cwebsite, $post_id);
        update_field('field_5bef1032743f9', $cphone, $post_id);
        update_field('field_5bef108a743fa', $caddress, $post_id);

        $success[] = array('code' => 200);
        echo json_encode($success);

        exit();
    }

    echo json_encode($errorMSG);

    exit();
}
add_action('wp_ajax_company_info', 'company_info');
add_action('wp_ajax_nopriv_company_info', 'company_info');
add_action('acf/save_post' , 'company_info', 20 );

图像字段的 HTML:

<div class="acf-field acf-field-image acf-field-5bef0fac743f7" style="width:50%;" data-name="company_logo" data-type="image" data-key="field_5bef0fac743f7" data-required="1" data-width="50">
  <div class="acf-label">
    <label for="acf-field_5bef0fac743f7">COMPANY LOGO <span class="acf-required">*</span></label>
  </div>

  <div class="acf-input">
    <div class="acf-image-uploader" data-preview_size="thumbnail" data-library="all" data-mime_types="" data-uploader="basic">
      <input name="acf[field_5bef0fac743f7]" value="url=C%3A%5Cfakepath%5C4change-energy-logo.png" type="hidden">

      <div class="show-if-value image-wrap" style="max-width: 150px">
        <img data-name="image" src="" alt="" class="pk-pin-it-ready">
        <div class="acf-actions -hover">
          <a class="acf-icon -cancel dark" data-name="remove" href="#" title="Remove"></a>
        </div>
      </div>

      <div class="hide-if-value">
        <label class="acf-basic-uploader">
                    <input name="acf[field_5bef0fac743f7]" id="acf-field_5bef0fac743f7" type="file">                           </label>

      </div>
    </div>
  </div>
</div>

标签: phpjquerywordpressadvanced-custom-fields

解决方案


删除 processData: false,并手动检查“ajaxurl”后面的 url。做这两件事必须避免得到 404


推荐阅读