programing

다운로드 없이 외부 URL에서 wordpress 피처링 이미지

kakaobank 2023. 3. 23. 22:55
반응형

다운로드 없이 외부 URL에서 wordpress 피처링 이미지

워드프레스에서 외부 사진을 특집 이미지로 사용하고 싶습니다.

WORDRESS 코드를 바꾸거나 합니다.(url에서 피처링된 이미지를 올바르게 표시하기 위해 url을 받아들이는 이미지 메타박스를 표시하고 몇 가지 변경을 수행합니다.)

또는 이미지 URL에서 피처 이미지를 설정하는 플러그인 WP 리모트 섬네일을 수정하여 이미지를 다운로드하고 워드프레스로 섬네일을 생성하여 피처 이미지를 설정합니다.

수정사항 : * URL에서 다운로드 할 수 없습니다.이 URL을 사용하여 블로그에 직접 표시할 수 있습니다.* wordpress에서 생성된 URL에서 wp-content/filength를 삭제하여 특집 이미지를 표시합니다(외부 URL에 한함). 썸네일은 생성되지 않습니다.

읽어주셔서 감사합니다.이 문제에 대해 많은 질문이 있다는 것을 알지만 이 문제를 해결한다면 많은 질문들에 도움이 될 것입니다.

코드는 다음과 같습니다.

<?php
/*
Plugin Name: WP Remote Thumbnail
Plugin URI: http://magnigenie.com/wp-remote-thumbnail-set-external-images-featured-image/
Description: A small light weight plugin to set external/remote images as post thumbnail/featured image.
Version: 1.0
Author: Nirmal Kumar Ram
Author URI: http://magnigenie.com
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/
?>
<?php

/**
 * Initialize wprthumb on the post edit screen.
 */
function init_wprthumb() {
    new wprthumb();
}

if ( is_admin() ) {
    add_action( 'load-post.php', 'init_wprthumb' );
    add_action( 'load-post-new.php', 'init_wprthumb' );
}


class wprthumb {

    /**
     * Hook into the appropriate actions when the wprthumb is constructed.
     */
    public function __construct() {
        add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
        add_action( 'save_post', array( $this, 'save' ) );
    }

    /**
     * Adds the meta box container.
     */
    public function add_meta_box( $post_type ) {
    if ( post_type_supports( $post_type, 'thumbnail' )) {
      add_meta_box(
        'some_meta_box_name'
        ,'Remote Post Thumbnail'
        ,array( $this, 'render_meta_box_content' )
        ,$post_type
        ,'side'
        ,'default'
      );
    }
    }

    /**
     * Save the meta when the post is saved.
     */
    public function save( $post_id ) {

        /*
         * We need to verify this came from the our screen and with proper authorization,
         * because save_post can be triggered at other times.
         */

        // Check if our nonce is set.
        if ( ! isset( $_POST['wprthumb_nonce'] ) )
            return $post_id;

        $nonce = $_POST['wprthumb_nonce'];

        // Verify that the nonce is valid.
        if ( ! wp_verify_nonce( $nonce, 'wprthumb' ) )
            return $post_id;

        // If this is an autosave, our form has not been submitted,
    // so we don't want to do anything.
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
            return $post_id;

        // Check the user's permissions.
        if ( 'page' == $_POST['post_type'] ) {

            if ( ! current_user_can( 'edit_page', $post_id ) )
                return $post_id;

        } else {

            if ( ! current_user_can( 'edit_post', $post_id ) )
                return $post_id;
        }

    /* All good, its safe for us to save the data now. */

        // Sanitize the user input.
        $image = sanitize_text_field( $_POST['remote_thumb'] );
    $upload_dir = wp_upload_dir();
    //Get the remote image and save to uploads directory
    $img_name = time().'_'.basename( $image );
    $img = wp_remote_get( $image );
    $img = wp_remote_retrieve_body( $img );
    $fp = fopen( $upload_dir['path'].'/'.$img_name , 'w');
    fwrite($fp, $img);
    fclose($fp);

    $wp_filetype = wp_check_filetype( $image , null );
    $attachment = array(
      'post_mime_type' => $wp_filetype['type'],
      'post_title' => preg_replace('/\.[^.]+$/', '', $image ),
      'post_content' => '',
      'post_status' => 'inherit'
    );

    //require for wp_generate_attachment_metadata which generates image related meta-data also creates thumbs
    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    $attach_id = wp_insert_attachment( $attachment, $image, $post_id );
    //Generate post thumbnail of different sizes.
    $attach_data = wp_generate_attachment_metadata( $attach_id , $image );
    wp_update_attachment_metadata( $attach_id,  $attach_data );
    //Set as featured image.
    delete_post_meta( $post_id, '_thumbnail_id' );
    add_post_meta( $post_id , '_thumbnail_id' , $attach_id, true);
    }

    /**
     * Render Meta Box content.
     */
    public function render_meta_box_content( $post ) {

        // Add an nonce field so we can check for it later.
        wp_nonce_field( 'wprthumb', 'wprthumb_nonce' );

        // Display the form, using the current value.
        echo '<label for="remote_thumb">';
        _e( 'Enter remote image url', 'wprthumb' );
        echo '</label> ';
        echo '<input type="text" id="remote_thumb" name="remote_thumb" size="25" />';
    }
}

리모트 URL의 이미지를 다운로드하지 않고 재업로드 할 수 있다는 것을 방금 알았습니다.이 기능은 기본적으로 Wordpress에서 작동하며 플러그인을 설치할 필요가 없습니다.

방법은 다음과 같습니다.

UPLOAD FILES가 표시되는 곳이라면 클릭해 주세요.파일 브라우저는 로컬 파일을 선택해야 하는 곳에 표시됩니다.단, 이 상자에 IMAGE URL을 붙여넣고 [OPEN]또는 [ENTER]를 누르면 Wordpress는 리모트 URL에서 이미지를 Import합니다.

원격 URL에서 이미지를 업로드하려면 SELECT FILES를 클릭합니다. 원격 URL에서 이미지를 업로드하려면 SELECT FILES를 클릭합니다.

원격 이미지 URL을 파일 이름이 있는 위치에 붙여넣습니다. 원격 이미지 URL을 파일 이름이 있는 위치에 붙여넣습니다.

이 플러그인은 필요한 기능을 하는 것 같습니다.https://wordpress.org/plugins/external-featured-image

여기에는 URL에서 플러그인 기능 이미지(FIFU)를 사용할 수 있습니다.

언급URL : https://stackoverflow.com/questions/22577566/wordpress-featured-image-from-external-url-without-download

반응형