Wordpress из guestform добавить изображение в post_content - PullRequest
1 голос
/ 07 февраля 2020

Я пытаюсь разрешить гостям публиковать события на моей странице WordPress через категории сообщений, им нужно установить миниатюру сообщения и еще 1-3 изображения для сообщения. Я добавил миниатюру поста с помощью set_post_thumbnail (), но я не могу понять и нашел что-то в кодексе WordPress, чтобы помочь мне, может быть, вы, ребята, знаете что-то, чтобы помочь мне на правильном пути? Код, который у меня есть:

//Upload Image
    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    require_once( ABSPATH . 'wp-admin/includes/file.php' );
    require_once( ABSPATH . 'wp-admin/includes/media.php' );
    $attachment_id = media_handle_upload('file',$post_id);
    $attachment_id2 = media_handle_upload('file2',$post_id);
    $attachment_id3 = media_handle_upload('file3',$post_id);
    $attachment_id4 = media_handle_upload('file4',$post_id);

//Set Image as thumbnail
    set_post_thumbnail($post_id, $attachment_id); 

1 Ответ

1 голос
/ 07 февраля 2020

Я нахожу этот вопрос немного расплывчатым, поэтому я отвечу тем, что, как мне кажется, вы имеете в виду.

Сначала вам потребуется атрибут enctype в вашей форме.

<form ... enctype="multipart/form-data">
    <input name="file" type="file">
    <input name="file2" type="file">
    <input name="file3" type="file">
    <input name="file4" type="file">
</form>

Теперь в вашем файле процесса вам нужно будет получить каждый файл из массива $_FILES.

<?php

    $file = !empty( $_FILES[ 'file' ] ) ? $_FILES[ 'file' ] : null;
    $file2 = !empty( $_FILES[ 'file2' ] ) ? $_FILES[ 'file2' ] : null;
    $file3 = !empty( $_FILES[ 'file3' ] ) ? $_FILES[ 'file3' ] : null;
    $file4 = !empty( $_FILES[ 'file4' ] ) ? $_FILES[ 'file4' ] : null;

И, наконец, вам понадобится пользовательская функция для обработки загрузки каждого файла. Вот тот, который я создал и использую в своих проектах (измененный для этого вопроса, поэтому, пожалуйста, проверьте!).

<?php

function my_asset_uploader( $file, $parent_id = 0, $allowed = [] ) {
    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/image.php';

    // Get basic attributes
    $filename   = basename( $file[ 'name' ] );
    $mime       = wp_check_filetype( $filename );

    // Get the content type from response headers
    $type   = !empty( $mime[ 'type' ] ) ? $mime[ 'type' ] : $file[ 'type' ];
    $ext    = !empty( $mime[ 'ext' ] ) ? $mime[ 'ext' ] : trim( explode( '|' , array_search( $type, get_allowed_mime_types() ) )[ 0 ] );

    // Basic checks
    if ( !$type || !$ext || ( !empty( $allowed ) && is_array( $allowed ) && !in_array( $ext, $allowed ) ) ) {
        // Not a valid file
        return new WP_Error( 'upload', 'Invalid file type. Please try another file.' );
    }

    // Move file to wp-content
    $body   = @file_get_contents( $file[ 'tmp_name' ] );
    $file   = wp_upload_bits( $filename, null, $body );

    // Upload check
    if ( !empty( $file[ 'error' ] ) ) {
        return new WP_Error( 'upload', $file[ 'error' ] );
    }

    // Write attachment location to the database
    $attachment_id = wp_insert_attachment( [
        'post_title'        => $filename,
        'post_mime_type'    => $file[ 'type' ]
    ], $file[ 'file' ], $parent_id, true );

    if ( is_wp_error( $attachment_id ) ) {
        return $attachment_id;
    }

    // Generate meta
    $attach_data = wp_generate_attachment_metadata( $attachment_id, $file[ 'file' ] );
    wp_update_attachment_metadata( $attachment_id, $attach_data );

    return $attachment_id;
}

Использование

<?php

/**
 * Extensions we allow the user to upload
 */
$allowed_extensions = [ 'jpg', 'jpeg', 'png', 'gif' ];

/**
 * Insert post
 */
$post_id = wp_insert_post( ... );

/**
 * Get all files from the request payload
 */
$all_images = array_filter( [
    !empty( $_FILES[ 'file' ] ) ? $_FILES[ 'file' ] : null,
    !empty( $_FILES[ 'file2' ] ) ? $_FILES[ 'file2' ] : null,
    !empty( $_FILES[ 'file3' ] ) ? $_FILES[ 'file3' ] : null,
    !empty( $_FILES[ 'file4' ] ) ? $_FILES[ 'file4' ] : null,
] );

/**
 * Uploaded files
 */
$attachment_ids = [];

/**
 * Check we have any images before looping
 */
if ( $all_images ) {
    foreach ( $all_images as $img_file ) {
        $this_id = my_asset_uploader( $img_file, $post_id, $allowed_extensions );

        if ( $this_id && !is_wp_error( $this_id ) ) {
            $attachment_ids[] = $this_id;
        }
    }
}

/**
 * Check at least one image was successfully uploaded
 */
if ( !empty( $attachment_ids[ 0 ] ) ) {
    set_post_thumbnail( $post_id, $attachment_ids[ 0 ] );
}

Это только отправная точка, которая поможет вам в правильном направлении.

Надеюсь, это поможет!


Редактировать

Добавление трех изображений в post_content ...

Если вы используете описанный выше процесс и у вас есть массив идентификаторов вложений, вы можете добавить изображение html для каждого вложения к содержимому публикации, например:

<?php

...

/**
 * Check at least one image was successfully uploaded
 */
if ( !empty( $attachment_ids[ 0 ] ) ) {
    set_post_thumbnail( $post_id, $attachment_ids[ 0 ] );
}

/**
 * We have multiple files, lets append them to the post_content
 */
if ( count( $attachment_ids ) > 1 ) {

    $appendage = '';

    foreach ( $attachment_ids as $i => $img_id ) {
        // Skip the first image because we used that as the thumbnail
        if ( $i === 0 ) continue;

        // Get the attachment HTML for a `large` sized image
        if ( $html = wp_get_attachment_image( $img_id, 'large' ) ) {
            $appendage .= $html;
        }
    }

    if ( !empty( $appendage ) ) {

        /**
         * Get the current post content
         */
        $current_content = get_post_field( 'post_content', $post_id, 'raw' );

        /**
         * Update the post
         */
        wp_update_post( [
            'ID' => $post_id,
            'post_content' => ( $current_content . $appendage ) // Joining the two strings
        ] );
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...