Lỗi không Update Meta_Value Khi thay thế hình ảnh cũ bằng hình ảnh mới trong WordPress

Mã dưới đây hoạt động tốt có 1 lỗi không update được postmeta ” meta_key=_thumbnail_id và meta_value=id tại sao ? 2 dòng dưới không thấy update //UPDATE meta_value // Finally! set our post thumbnail <?php class Auto_Save_Images_local { function __construct() { add_filter( 'content_save_pre', array( $this, 'post_save_images' ) ); } function post_save_images( $content ) { if

Mã dưới đây hoạt động tốt có 1 lỗi không update được postmeta ” meta_key=_thumbnail_id và meta_value=id tại sao ?

2 dòng dưới không thấy update

//UPDATE meta_value

// Finally! set our post thumbnail

<?php

class Auto_Save_Images_local {
    function __construct()
    {
        add_filter( 'content_save_pre', array( $this, 'post_save_images' ) );
    }
    function post_save_images( $content )
    {
        if ( ( isset( $_POST['save'] ) || isset( $_POST['publish'] ) ) ) {
            set_time_limit( 240 );
            global $wpdb, $post;
            $post_id = $post->ID;
            $preg = preg_match_all( '/<img.*?src="(.*?)"/', stripslashes( $content ), $matches );
            if ( $preg ) {
                foreach ( $matches[1] as $image_url ) {
                    if ( empty( $image_url ) ) continue;
                    if ( get_option( 'upload_url_path' ) ) {
                        $checkdomain = @parse_url( get_option( 'upload_url_path' ) );
                        $domain = isset( $checkdomain['host'] ) ? $checkdomain['host'] : '' . $_SERVER['HTTP_HOST'] . '';
                    } else {
                        $domain = $_SERVER['HTTP_HOST'];
                    }
                 
                    $pos = !empty( $domain ) && strpos( $image_url, $domain ) ? strpos( $image_url, $domain ) : FALSE;
                    if  ($pos === FALSE ) {
                        //LINK NGOAI
                        //$res = $this->save_images( $image_url, $post_id );
                        //$replace = $res['url'];
                        //$content = str_replace( $image_url, $replace, $content );
                    } else {
                        //LINK TRONG
                        //Get the name file
                        $info_file = pathinfo( $image_url );
                        if ( $info_file['extension'] === "webp" ) continue;
                     
 
                        $image_url_old = $image_url;
                        $res = $this->save_images( $image_url, $post_id );
                        $replace = $res['url'];
                        $content = str_replace( $image_url, $replace, $content );

                        $thumb_attach_id = attachment_url_to_postid( $image_url );
                       
                       //UPDATE meta_value không thấy update
                        $wpdb->query(
                            "UPDATE $wpdb->postmeta
                            SET meta_value = $thumb_attach_id
                            WHERE post_id = $post_id AND meta_key = '_thumbnail_id' AND meta_value <> '0'"
                        );
                      
                    }
                }
            }
        }
        remove_filter( 'content_save_pre', array( $this, 'post_save_images' ) );
        return $content;
    }
    
    function save_images( $image_url, $post_id )
    {
        $stream_opts = [
            "ssl" => [
                "verify_peer" => false,
                "verify_peer_name" => false,
                "ciphers" => "DEFAULT:!DH",
            ]
        ];

        $file = file_get_contents( $image_url, false, stream_context_create( $stream_opts )  );
        $set_ext_image = '.webp';

        $post = get_post( $post_id );
        $posttitle = $post->post_title;
        $postname = sanitize_title( $posttitle );
        //$im_name = "$postname-$post_id.jpg"; 
        $im_name = "$postname-$post_id". $set_ext_image; 
        $res = wp_upload_bits( $im_name, '', $file );
        $this->insert_attachment( $res['file'], $post_id );
        return $res;
    }
    function insert_attachment( $filename, $post_id )
    {
        // the file must be in the WP uploads directory. // tệp phải nằm trong thư mục tải lên WP.
        //$filename = '/path/to/uploads/2013/03/filname.jpg';

        // Get the path to the uploads directory. // Lấy đường dẫn đến thư mục uploads.
        $dirs = wp_upload_dir();

        // the ID of the post to which we are attaching. // ID của bài đăng mà chúng tôi đang đính kèm.
        //$parent_post_id = $post_id;

        // Check the post type that we use in the 'post_mime_type' field. // Kiểm tra loại bài đăng mà chúng tôi sử dụng trong trường 'post_mime_type'.
        $filetype = wp_check_filetype( basename( $filename ), null );
 
        $post = get_post( $post_id );
        $posttitle = $post->post_title;

        if ( isset( $posttitle ) ) {
            $attachment = array(
                //'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ), 
                'guid' => $dirs['baseurl'] . '/' . _wp_relative_upload_path( $filename ),
                'post_mime_type' => $filetype['type'],
                'post_title'   => sanitize_text_field( $posttitle ), //sanitize_text_field( $title ),
                'post_excerpt' => sanitize_text_field( $posttitle ), //sanitize_text_field( $caption ),
                'post_content' => sanitize_text_field( $posttitle  ), //sanitize_text_field( $description ),
                'post_status'  => 'inherit'
            );

        } else {
            $attachment = array(
                //'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ), 
                'guid' => $dirs['baseurl'] . '/' . _wp_relative_upload_path( $filename ),
                'post_mime_type' => $filetype['type'],
                'post_title' => preg_replace( '/.[^.]+$/', '', basename( $filename ) ),
                'post_excerpt' => preg_replace( '/.[^.]+$/', '', basename( $filename ) ),
                'post_content' => preg_replace( '/.[^.]+$/', '', basename( $filename ) ),
                'post_status' => 'inherit'
            );

        }

        // Insert the attachment into the database. // Chèn tệp đính kèm vào cơ sở dữ liệu.
        $attach_id = wp_insert_attachment( $attachment, $filename, $post_id ); // $thumb_id = $attach_id

        //require_once( ABSPATH . 'wp-admin/includes/image.php' );

        $attach_data = wp_generate_attachment_metadata( $attach_id, $filename ); // $metadata = $attach_dat
        wp_update_attachment_metadata( $attach_id, $attach_data );

        // Finally! set our post thumbnail
        //update_post_meta( $post_id, '_thumbnail_id', $attach_id ); // KO THAY UPDATE
 

        return $attach_id;
    }
}
new Auto_Save_Images_local();

Nguồn: viblo.asia

Bài viết liên quan

Check nameservers của tên miền xem website trỏ đúng chưa

Tìm hiểu cách check nameservers của tên miền để xác định tên miền đó đang dùn

Mình đang dùng Google Domains để check tên miền hàng ngày

Từ khi thông báo dịch vụ Google Domains bỏ mác Beta, mình mới để ý và bắt đầ

Cách sử dụng SFTP (Giao thức truyền file qua SSH an toàn hơn)

SFTP là cách an toàn để truyền files giữa các máy tính, gữa máy local và web hostin

Hotlinking: Key Reasons to Avoid and Methods to Protect Your Site

Hotlinking might seem an easy way to acquire website assets, but in reality, it brings several disad