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">×</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.