0

I have the link of WordPress doc about this function, but there is nothing explaining how to use this. I have a Ajax function, PHP and a HTML input. In this HTML I set the title and content, and I'd like to set the thumbnail too. Maybe I can do that with this function? Is there some example?

https://developer.wordpress.org/reference/functions/wp_ajax_set_post_thumbnail/

[EDIT]

I have an html input

<input type="file">

I have an AJAX Call

$.ajax({
    url: Ajax.ajax_url,
    type: 'POST',
    data: {
        action: 'make_the_post_activity',
        security: Ajax.nonce,
        dataType: 'json'
    },
    success: function( response ){

    }
   });

And a PHP function

add_action('wp_ajax_make_the_post_activity', 'make_the_post_activity');
add_action('wp_ajax_nopriv_make_the_post_activity', 'make_the_post_activity');
function make_the_post_activity(){
  if( check_ajax_referer('namorada-security-ajax', 'security', false) ){
    // Here inside I add the the new post calling by ajax the fields as title and content from the HTML file.
  }
}

Then here I get the ID of the New Post. But I don't know how to update this new post id with the image from the input (file). I know that the Ajax can't upload the image with XMLHttpRequest, but I'm sure there is another possibility that I still don't know.

I understand the function that the friend added bellow, but in this condition, I need already pass maybe sending a JSON to the Ajax function, the ID of the image I've uploaded in the wordpress library, but I don't know how to upload it and get the ID to send to Ajax and then publish it via REST API.

[EDIT 2] I'll put here the complete functions I use to upload the photo with Ajax and PHP, and the fiels I need to use to make the new post, maybe it will be a big amount of code.

HTML

<div class="modal-dialog vertical-align-center" role="document">
   <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel"><?php echo __('Escreva seu post', 'namorada-general'); ?></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
         <form action="" method="post" enctype="multipart/form-data">
           <div class="form-group">
              <textarea class="form-control input_activity_content" id="post_activity_form_emoji" data-emoji-placeholder=":smiley:"></textarea>
            </div>
            <div style="width:100%;float:left;">
              <i class="fa fa-image p-1 upload_photo_activity" style="float:right;font-size:20px;cursor:pointer;"></i>
              <i class="fa fa-video-camera p-1 youtube_video_activity" style="float:right;font-size:20px;cursor:pointer;"></i>
             </div>
             <div style="width:100%;float:left;display:none;" id="youtube_video_activity">
               <div class="input-group mb-3">
                <div class="input-group-prepend">
                 <span class="input-group-text" id="inputGroup-sizing-default">YouTube</span>
                 </div>
                 <input type="text" class="form-control input_youtube_video_activity" aria-label="Default" aria-describedby="inputGroup-sizing-default">
                </div>
            </div>
            <div style="width:100%;float:left;display:none;" id="upload_photo_activity">
            <div class="custom-file">
                <input type="file" class="custom-file-input input_upload_photo_activity" id="packagephoto" name="packagephoto">
                <label class="custom-file-label choose_photo_activity" for="validatedCustomFile" accept="image/x-png,image/gif,image/jpeg">Escolha sua foto</label>
                <div class="invalid-feedback">Example invalid custom file feedback</div>
                </div>
            </div>
            </form>
        </div>
        <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo __('Cancelar', 'namorada-general'); ?></button>
        <input id="addimage" name="addimage" class="btn btn-primary make_the_post_activity" value="<?php echo __('Publicar', 'namorada-general'); ?>">
         </div>
    </div>
</div>

The AJAX Functions (I have one function I use to insert the POST (the first) and another that I use to insert the image in my own database (the second), and I don't know how to connect this image with the featured image of this new post.

[first AJAX function]

$('.make_the_post_activity').live('click', function(){

        var post_activity_video_url = $('.input_youtube_video_activity').val();
        var post_activity_image_url = $('.input_upload_photo_activity').val();
        var post_activity_content = $('.input_activity_content').val();

        $.ajax({

            url: Ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'make_the_post_activity',
                security: Ajax.nonce,
                dataType: 'json',
                user_id: user_id,
                girl_page_author: girl_page_author,
                post_activity_video_url: post_activity_video_url,
                post_activity_image_url: post_activity_image_url,
                post_activity_content: post_activity_content
            },
            success: function( response ){
                if( response.hasOwnProperty('status') ){
                    alert( response.message );
                }
            },
            error: function( error ){

            },
            complete: function(){

            }

        });

});

And this this AJAX Function, I have the Action with this First PHP Function

[PHP Function for the Previous AJAX Function]

add_action('wp_ajax_make_the_post_activity', 'make_the_post_activity');
add_action('wp_ajax_nopriv_make_the_post_activity', 'make_the_post_activity');
function make_the_post_activity(){

    if( check_ajax_referer('namorada-security-ajax', 'security', false) ){

        $user_id = $_REQUEST['user_id'];
        $garota_id = $_REQUEST['garota_id'];
        $girl_page_author = $_REQUEST['girl_page_author'];
        $post_activity_video_url = $_REQUEST['post_activity_video_url'];
        $post_activity_image_url = $_REQUEST['post_activity_image_url'];
        $post_activity_content = $_REQUEST['post_activity_content'];

        if( is_user_logged_in() && current_user_can('publish_posts') && $user_id == $girl_page_author ){

            $args = array(
            'post_author' => $user_id,
            'post_content' => $post_activity_content,
            'post_title' => __('Nova postagem de', 'namorada-general'),
            'post_type' => 'post-activity',
            'post_status' => 'publish'
            );

            $new_post = wp_insert_post( $args );

            if( isset($new_post) ){

                // Save the YouTube URL when it exists
                if( isset($post_activity_video_url) && $post_activity_video_url != '' ){
                    $field_key_video_url_youtube_post_activity = 'field_5f08ca584384d';
                    update_field( $field_key_video_url_youtube_post_activity, $post_activity_video_url, $new_post );
                }

                // Save the Featured Image of the Post when it exists
                $field_key_image_url_post_activity = 'field_5f08ca6d4384e';
                update_field( $field_key_image_url_post_activity, $post_activity_image_url, $new_post );

                $response = array(
                'status' => 'success',
                'message' => 'Your post was published'
                );

            }

        } else {
            $response = array(
                'status' => 'fail',
                'message' => 'you are not the author'
            );
        }

    } else {

        $response = array(
            'status' => 'fail',
            'message' => 'it is not passing by the ajax referer'
        );

    }

    wp_send_json( $response );

}

AND THEN, I have the SECOND AJAX FUNCTION - To add the Image (from the HTML Input with the others fields).

[SECOND AJAX FUNCTION]

$('#addimage').click(function(e) {
    var packagename = $('#packagename').val();
    var packagephoto_data = $('#packagephoto').prop('files')[0];

    var form_data = new FormData();

    form_data.append('packagephoto_name', packagephoto_data);
    form_data.append('packagename', packagename);
    form_data.append('action', 'ng_add_image_ajax');
    
    $.ajax({
        url: Ajax.ajax_url,
        type: 'post',
        contentType: false,
        processData: false,
        data: form_data,
        success: function(data){

        }

    });
});

And this function, has this next PHP Function as the ACTION

[PHP FUNCTION FOR THE PREVIOUS AJAX CALL]

function ng_add_image_ajax() {

    add_filter( 'upload_dir', 'ng_upload_dir' );    
    global $wpdb;
    $tablename = $wpdb->prefix . 'imagepackages';
    
    $uploadedfile = $_FILES['packagephoto_name'];
    $packagephoto_name = $_FILES["packagephoto_name"]["name"];
    $upload_overrides = array( 
        'test_form' => false, /* this was in your existing override array */
        'unique_filename_callback' => 'ng_packagephoto_filename' // Function for image rename
    );
    $movefile = wp_handle_upload($uploadedfile, $upload_overrides);
    if ($movefile && !isset($movefile['error'])) {
    $data = array( 
    'packagename' => $_POST['packagename'],
    'packagephoto' => ng_packagephoto_filename('', $packagephoto_name, ''),
    'status' => 0 );

    // FOR database SQL injection security, set up the formats
    $formats = array( 
        '%s', // packagename should be an string
        '%s', // packagephoto should be a integer
        '%d'  // status should be an integer 
    ); 
    // Actually attempt to insert the data
    $insert = $wpdb->insert($tablename, $data, $formats);
    if($insert){
    echo "<span class='text-success'>The image has been added succefully</span>";
    }else{
    echo "<span class='text-danger'>The image not added succefully</span>"; 
    }
    }else{
        echo "<span class='text-danger'>Image Not Upload</span>";
    }
    remove_filter( 'upload_dir', 'ng_upload_dir' );
}
add_action( 'wp_ajax_ng_add_image_ajax', 'ng_add_image_ajax' );    // If called from admin panel
add_action( 'wp_ajax_nopriv_ng_add_image_ajax', 'ng_add_image_ajax' );


function ng_packagephoto_filename($dir, $filename, $ext){
    $newfilename =  time() . '1_'. $filename;
    return $newfilename;
}

function ng_upload_dir( $dirs ) { 
$user = wp_get_current_user(); 
$dirs['subdir'] = ''; 
$dirs['path'] = $dirs['basedir'].''; 
$dirs['url'] = $dirs['baseurl'].'';
return $dirs; 
}

Saying again, this second AJAX function, add upload the image using the FormData(). Then there is a way to connect this formData with the Media Library and then make this photo as the Featured Image of the Post.

Sorry, I know it is big and unpleasant to read like that.

7
  • happy to help, but I don't quite understand the problem. Maybe if you state it in terms of what you have and what you want to do that would be useful, and if you want to do this from PHP inside Wordpress, or from the browser
    – mozboz
    Jul 13 '20 at 22:45
  • I have a form in the front-end where the user write a content, and upload an image. And this text with this image will be queried in his page. Like an activity of a social media. Now what I have is the content that the user write and publish with Ajax. But I can't get this input file with the image and turn it as a featured image of this post that is made with this input of text. I need that the user insert the text and the image, and I get it into a post-type with the content and the featured image, then I can display it in his timeline as a post of a social media. Is it better now? Ask me pl Jul 13 '20 at 23:15
  • You have a form that will take some text and an image, and you want this to become a new post, with the image as the featured image? And you want that to happen by AJAX rather than page reload? (You could also do it by page reload which would probably be easier)
    – mozboz
    Jul 13 '20 at 23:18
  • Yes, I can write the text content and make it a new post, but without the featured image. I understand, maybe it is too hard to do and it is better to make reloading the page. Jul 13 '20 at 23:22
  • I can even upload an image to my own plugin database with Ajax, but I can't make this the featured image. Jul 13 '20 at 23:24
0

Assuming you're looking at calling this via an AJAX style call from your browser, I'd suggest you look at the new Wordpress REST API.

Here's the docs for the endpoint for updating posts. This will allow you to do exactly the same thing with the featured_media parameter, and much more, and is likely much better documented.

https://developer.wordpress.org/rest-api/reference/posts/#update-a-post

EDIT:

Here's a quick example of using jQuery to do a POST to update the ID of the featured media to 456 on post ID 123. This is a quick example and untested to give you an example of how this works with jQuery, but please reply if you have errors so it can be updated.

    var postID = 123
    var imageID = 456
    var apiURL = "https://yoursite.com/wp-json/wp/v2/posts/"
    var thisPostURL = apiURL + postID
    $.post( thisPostURL, 
            { 'featured_media' : imageID }
          );

EDIT 2:

Not sure if this will get you all the way, but the function to set the featured image when you're in PHP is set_post_thumbnail

So if you can call your plugin after the image is uploaded, you just need the post ID and the new image ID and you can do this in PHP:

set_post_thumbnail($postId, $imageID);

EDIT 3:

So it's unclear what you're trying to do in the PHP you pasted with inserting into the imagepackages table directly, but you need to use wp_insert_attachment to be able to upload an image into Wordpress's media library, and then get an ID which you can use to easily make this image the featured image. If you want to upload your file somewhere else and do something else with it, you should probably still do wp_insert_attachment afterwards, otherwise it won't be possible to easily use the image in Wordpress.

Here's an example taken from the comments in the previously linked page which shows how to add an image and then use the ID returned to set it as the featured image.

    // Insert the attachment.
    $attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );

    // Make sure that this file is included, as         wp_generate_attachment_metadata() depends on it.
    require_once( ABSPATH . 'wp-admin/includes/image.php' );

    // Generate the metadata for the attachment, and update the database record.
    $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
    wp_update_attachment_metadata( $attach_id, $attach_data );

    set_post_thumbnail( $parent_post_id, $attach_id );
9
  • It is very interesting, I'm looking that. It would be a very good thing if you have an example. I didn't put my function, because it is very simple, a html input, ajax call and php action. Jul 13 '20 at 20:44
  • @GabrielBorges example added,
    – mozboz
    Jul 13 '20 at 20:54
  • Sorry if I'll be boring, if you don't want to answer I already thank you very much. But I'm still a little confused. I'll add an edit of my post. Jul 13 '20 at 22:00
  • Sure, happy to help - or start a new question if it's a new question
    – mozboz
    Jul 13 '20 at 22:03
  • 1
    my friend! It was not easy, but I'm proud of myself (because it was a big challenge for a beginner) and very thankful for you too. I did the upload system in the front end using ajax (no reloading the page). I'll answer my own question with the answer. I used what you gave me. Jul 15 '20 at 1:24
0

I used the HTML input to save the image, as you can see below.

<form enctype="multipart/form-data">
<input type="text" name="support_title" class="support-title">
<input type="file" id="sortpicture" name="upload">
<input class="save-support" name="save_support" type="button" value="Save">
</form>

And then, I used the AJAX with the formData object to upload the image.

$(document).on('click', '.save-support', function (e) {

     var supporttitle = $('.support-title').val();

     var querytype = $('.support-query').val();
     var file_data = $('#sortpicture').prop('files')[0];

     var form_data = new FormData();

     form_data.append('file', file_data);
     form_data.append('action', 'md_support_save');
     form_data.append('supporttitle', supporttitle);

     $.ajax({
     url: Ajax.ajax_url,
     type: 'post',
     contentType: false,
     processData: false,
     data: form_data,
     success: function (response) {
     }
   });
});

And finally the PHP function to get this image from formData and handle as a WordPress image, and in the end, set this image as featured image.

add_action( 'wp_ajax_md_support_save','md_support_save' );
add_action( 'wp_ajax_nopriv_md_support_save','md_support_save' );
function md_support_save(){
       $support_title = !empty($_POST['supporttitle']) ? 
       $_POST['supporttitle'] : 'Support Title';

        if (!function_exists('wp_handle_upload')) {
           require_once(ABSPATH . 'wp-admin/includes/file.php');
       }
      $uploadedfile = $_FILES['file'];
      $upload_overrides = array('test_form' => false);
      $movefile = wp_handle_upload($uploadedfile, $upload_overrides);

    $filename = $movefile['url'];;
     
    // The ID of the post this attachment is for.
    $parent_post_id = 173;
     
    // Check the type of file. We'll use this as the 'post_mime_type'.
    $filetype = wp_check_filetype( basename( $filename ), null );
     
    // Get the path to the upload directory.
    $wp_upload_dir = wp_upload_dir();
     
    // Prepare an array of post data for the attachment.
    $attachment = array(
        'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ), 
        'post_mime_type' => $filetype['type'],
        'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
        'post_content'   => '',
        'post_status'    => 'inherit'
    );
     
    // Insert the attachment.
    $attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
     
    // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
    require_once( ABSPATH . 'wp-admin/includes/image.php' );
     
    // Generate the metadata for the attachment, and update the database record.
    $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
    wp_update_attachment_metadata( $attach_id, $attach_data );
     
    set_post_thumbnail( $parent_post_id, $attach_id );

    die();
 }

And it is working now. Thanks @mozboz, you helped me a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.