首頁>Web>source

我有關於此功能的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上傳圖像,但是我敢肯定還有一種我仍然不知道的可能性。

我了解朋友添加的功能,但是在這種情况下,我需要將可能已经發送過JSON的AJSON傳遞给Ajax函式,這是我在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 (我有一个用於插入POST的功能(第一个),還有另一个用於將圖像插入自己的資料庫中的功能(第二个),而且我不知道如何將此圖像与该圖像的特色圖像連線 新帖子。

[第一个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函式作為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; 
}

再說一遍,這第二个AJAX函式使用FormData()添加上傳圖像.然後,有一種方法可以將此formData与媒體庫連線起来,然後將這张照片製作為Post的特色圖片。

對不起,我知道這樣阅讀会很大且令人不快。

最新回復
  • 11月前
    1 #

    假設您正在通過瀏覽器通過AJAX樣式呼叫来呼叫它,那麼建議您查看一下 新的wordpress REST API。

    這是端點的文件,用於更新帖子.這將使您可以對 featured_media做完全相同的事情 引數等等,並且可能会記錄得更好。

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

    編輯:

    這是一个使用jQuery进行POST来將帖子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

    因此,如果您可以在圖片上傳後呼叫插件,則只需提供帖子ID和新的圖片ID,即可在PHP中執行此操作:

    set_post_thumbnail($postId, $imageID);

    編輯3:

    因此,不清楚要在直接粘贴到imagepackages表中粘贴的PHP中要做什麼,但是您需要使用wp_insert_attachment才能將圖像上傳到wordpress的媒體庫中,然後获取一个ID 您可以轻松地使该圖像成為特色圖像.如果您想將檔案上傳到其他地方並进行其他操作,那麼以後您可能仍應该執行wp_insert_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 );
    

  • 11月前
    2 #

    我使用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,您帮了我很多忙。

  • wordpress:將靜態網站移至wordPress
  • wordpress:在yoast SEO中為分頁鏈接修複了鏈接rel =" next"