如何使用wp_ajax_set_POST_THMBETAILE?

时间:2020-07-13 作者:Gabriel Borges

我有关于这个功能的WordPress文档链接,但没有解释如何使用这个功能。我有一个Ajax函数、PHP和一个HTML输入。在这个HTML中,我设置了标题和内容,还想设置缩略图。也许我可以用这个函数来实现?有什么例子吗?

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

[EDIT]

我有一个html输入

<input type="file">
我接到一个AJAX电话

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

    }
   });
和一个PHP函数

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.
  }
}
然后在这里我得到了新帖子的ID。但我不知道如何用输入(文件)中的图像更新这个新的帖子id。我知道Ajax不能用XMLHttpRequest上传图像,但我确信还有另一种可能性,我仍然不知道。

我理解这位朋友在下面添加的函数,但在这种情况下,我需要向Ajax函数发送一个JSON,我上传到wordpress库中的图像的ID,但我不知道如何上传它,如何将ID发送到Ajax,然后通过REST API发布它。

[EDIT 2]我将在这里介绍使用Ajax和PHP上传照片所需的完整功能,以及制作新帖子所需的领域,可能需要大量代码。

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 (我有一个用于插入帖子的函数(第一个)和另一个用于将图像插入我自己的数据库(第二个),我不知道如何将此图像与此新帖子的特色图像连接。

[第一个AJAX函数]

$(\'.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(){

            }

        });

});
这个AJAX函数,我有了第一个PHP函数的动作

[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 );

}
然后,我有了第二个AJAX函数—添加图像(来自HTML输入和其他字段)。

[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){

        }

    });
});
这个函数将下一个PHP函数作为动作

[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; 
}
再说一遍,这是第二个AJAX函数,使用FormData()添加上传图像。然后有一种方法可以将此formData与媒体库连接,然后将此照片作为帖子的特色图像。

对不起,我知道这样读太多太不愉快了。

3 个回复
最合适的回答,由SO网友:mozboz 整理而成

假设您希望通过浏览器中的AJAX风格调用,我建议您看看新的Wordpress restapi。

以下是用于更新帖子的端点的文档。这将允许您对featured_media 参数等,并且可能有更好的文档记录。

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

编辑:

下面是一个使用jQuery发布帖子的快速示例,在帖子ID 123上将特色媒体的ID更新为456。这是一个未经测试的快速示例,为您提供了一个如何使用jQuery的示例,但如果您有错误,请回复,以便更新。

    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 }
          );
编辑2:

不确定这是否会一直帮助您,但在PHP中设置特色图像的函数是set_post_thumbnail

因此,如果您可以在上传图像后调用插件,您只需要post ID和新的图像ID,您可以在PHP中执行此操作:

set_post_thumbnail($postId, $imageID);

编辑3:

因此,不清楚您在粘贴的PHP中要做什么,直接插入到imagepackages表中,但您需要使用wp_insert_attachment 能够将图像上传到Wordpress的媒体库中,然后获得一个ID,您可以使用该ID轻松地将此图像作为特色图像。如果您想将文件上传到其他地方并对其执行其他操作,您可能仍然应该在之后执行wp\\u insert\\u attachment,否则无法在Wordpress中轻松使用图像。

下面是一个从之前链接的页面中的注释中提取的示例,它显示了如何添加图像,然后使用返回的ID将其设置为特色图像。

    // 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 );

SO网友:Gabriel Borges

我使用HTML输入来保存图像,如下所示。

<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>
然后,我使用AJAX和formData对象来上传图像。

$(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) {
     }
   });
});
最后,使用PHP函数从formData获取此图像并将其处理为WordPress图像,最后将此图像设置为特征图像。

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();
 }
现在它正在发挥作用。谢谢@mozboz,你帮了我很多。

SO网友:Francisco

也添加到此主题。

我也是一个初学者,在这里做了我的第一个AJAX调用。

我正试着从邮局取美元->;ID将AJAX提交到当前帖子中。学得很快,我无法将全局变量传递给AJAX php,因此我不得不使用$post->;添加一个新的隐藏输入字段;ID作为值,并附加Ajax表单数据以包含它。

下面是一个工作片段,用于在产品页面上添加前端图像上载。我相信可以改进。

$user = wp_get_current_user();
$allowed_roles = array( \'administrator\' );

if ( array_intersect( $allowed_roles, $user->roles ) ) {
add_action( \'woocommerce_before_single_product_summary\', \'add_image_uploader\', 10 );
add_action( \'wp_ajax_md_support_save\',\'md_support_save\' );
add_action( \'wp_ajax_nopriv_md_support_save\',\'md_support_save\' );
add_action(\'wp_footer\', \'tutsplus_add_script_wp_footer\');
add_action( \'woocommerce_before_single_product_summary\', \'add_postid\', 10 );
}

function add_image_uploader( $query ) {
global $product;
global $post;
if ( $product->get_sku() && current_user_can( \'edit_posts\' ) ) {
    
echo \'<h1>Upload Image</h1>\';
echo \'<div style="overflow: auto;background-color:#f5f5f5;padding:20px;width:100%;display:block;margin: 20px 0;border-radius:3px;">\';
echo \'<img id="output" width="100" height="100" style="display:inline-block;float:left;background-color:#fff;">\';
echo \'<form enctype="multipart/form-data" style="display:inline-block;">\';
echo \'<input type="hidden" name="post_id" id="post_id" value="\'. $post->ID . \'" readonly>\';
echo \'<input type="hidden" name="support_title" class="support-title" value="\'. $product->get_sku() . \'">\';
echo \'<input type="file" id="sortpicture" name="upload" onchange="myFunction();loadFile(event);" style="
padding: 15px;
margin: 0;
background-color: #fff;">\';
echo \'<input class="save-support" name="save_support" id="uploadbutton" type="button" value="Upload" disabled>\';
echo \'<p id="imagealert" style="color:green;margin:20px;font-size:1.3rem;"></p>\';
echo \'</form>\';
echo \'</div>\';
}
}

add_action(\'wp_head\', \'myplugin_ajaxurl\');
function myplugin_ajaxurl() {
   echo \'<script type="text/javascript">
           var ajaxurl = "\' . admin_url(\'admin-ajax.php\') . \'";
         </script>\';
}

function md_support_save(){
    
    $support_title = !empty($_POST[\'supporttitle\']) ? 
    $_POST[\'supporttitle\'] : \'Support Title\';
    $post_id = $_POST[\'post_id\'];
    
    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 = $_POST[\'post_id\'];
  
    // 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_name\'   => \'testpop\',
        \'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();
    
 }


/* Inline script printed out in the footer */
function tutsplus_add_script_wp_footer() { ?>
<script>
function myFunction() {     
    if( document.getElementById("sortpicture").files.length == 0 ) {
        document.getElementById("uploadbutton").disabled = true;
    } else {document.getElementById("uploadbutton").disabled = false;
            document.getElementById("imagealert").textContent = \'Image ready. Click Upload.\';
           }
};
            
var loadFile = function(event) {
    var output = document.getElementById(\'output\');
    output.src = URL.createObjectURL(event.target.files[0]);
    output.onload = function() {
        URL.revokeObjectURL(output.src) // free memory
    }
};
    
jQuery(document).on(\'click\', \'.save-support\', function (e) {
    var post_id = jQuery(\'#post_id\').val();
    var supporttitle = jQuery(\'.support-title\').val();
    var querytype = jQuery(\'.support-query\').val();
    var file_data = jQuery(\'#sortpicture\').prop(\'files\')[0];

    var form_data = new FormData();

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

    jQuery.ajax({
    url: ajaxurl,
    type: \'post\',
    contentType: false,
    processData: false,
    data: form_data,
    success: function (response) {
        alert(\'Image updated succesfully\');
        location.reload();
    }
    });
});
</script>
<?php 
}