front end - Add a post with react and axios

admin2025-04-17  0

I tried to add a post from the front end with react and axios, the post added successfully with just the title but the featured image is empty, and when i checked the media the image is miising.Bellow is my version of the code : React :

import React, { useState, useEffect } from "react";
import AxiosPost from "./axios-post";

const Add = () => {
  const [inputs, setInputs] = useState({title: "",imagefile: ""});

  const [data, setData] = useState(null);

  const handleInputsChange = event => {
    const target = event.target;
    const value = target.type === "checkbox" ? target.checked : target.value;
    const name = target.name;

    setInputs(prevState => {
        return { ...prevState, [name]: value };
    });
  };

  const handleFileChange = event => {
    const target = event.target;
    const name = target.name;
    const value = event.target.files[0];

    setInputs(prevState => {
      return { ...prevState, [name]: value };
    });
  };
const setResponse = (res)=>{console.log(res)}

  const submitForm = event => {

    event.preventDefault()
    let data = {
      author:"1",
      title: inputs.title,
      imagefile: inputs.imagefile
    };

    setData(data);
  };


  return (
    <section id="ajouterpost" className="section">

            <form id="form1" name="form1" method="post">
              <div className="form-group">
                <input onChange={handleInputsChange} value={inputs.title} name="title" type="text"/>
              </div>

              <div className="form-group">
                <input type="file" onChange={handleFileChange} name="imagefile" accept="image/*" />
              </div>

              <div className="form-group">
                <button onClick={event => {submitForm(event);}} name="submit" type="submit" >
                  send
                </button>
              </div>
            </form>
            {data && (
              <AxiosPost endpoint="addpost" data={data} setResponse={setResponse} />
            )}

            {successMessage && (
              <div dangerouslySetInnerHTML={{ __html: successMessage }} />
            )}

    </section>
  );
};

export default Add;

axios-post.js :

import React from "react";
import { usePostAPI } from "../States/reducer";

const AxiosPost = ({ endpoint, data, setResponse }) => {

  let response = usePostAPI(endpoint, data);

  return (
    <div>
      {response && response.data >= 0 && setResponse(response.data)}
    </div>
  );
};

export default AxiosPost;
export const usePostAPI = (endpoint, data) => {

  const [response, setResponse] = useState(null);

  useEffect(() => {
    getData();
  }, [endpoint]);

  const getData = async () => {
    const response2 = await axios.post(JSONLINK + endpoint, data, {
      headers: {
        "X-WP-Nonce": window.myData.nonce,
        "Content-type":"multipart/form-data; charset=utf-8; boundary=" + Math.random().toString().substr(2)}
    });
    setResponse(response2);
  };

  return response;
};

php file :

function addPost( WP_REST_Request $request )

    {


      $files = $request->get_file_params();

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

        $wpauthor = intval( get_current_user_id() );

        if ( !$wpauthor ) return rest_ensure_response( "You are not logged in" );

        $subject = sanitize_text_field(trim( $request['title'] ));


        // Create post object
        $my_post = array(
          'post_type' => 'post',
          'post_title'    => wp_strip_all_tags( $subject ),
          'post_author'   => get_current_user_id(),
          'post_status'   => 'publish',

        );


        $inserted_post = wp_insert_post( $my_post );



        if ( $inserted_post || !is_wp_error($inserted_post) ) {

             foreach ($files as $file => $array){
            $attachment_id = media_handle_upload( $file, $inserted_post )
        }

        if($attachment_id > 0) update_post_meta( $inserted_post, '_thumbnail_id', $attachment_id, $prev_value:mixed )

            return rest_ensure_response( "Post added successfully" );
        }

        return rest_ensure_response( "something wrong" );
    }
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744884958a272480.html

最新回复(0)