计划在下载时发布图像

时间:2018-09-29 作者:TravelWhere

我有很多包含外部图像的日程帖子,我希望能够自动下载图像&;发布状态更改为发布时链接到媒体库。

这是目前为止的代码,但不起作用:

<?php  
/*  
Plugin Name: NA
Version: 1.0
*/
add_action(\'future_to_publish\', \'fetch_images\', 10, 1);

function fetch_images( $post_ID )  
{   
    //Check to make sure function is not executed more than once on save
    if ( defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE ) 
    return;

    if ( !current_user_can(\'edit_post\', $post_ID) ) 
    return;

    remove_action(\'future_to_publish\', \'fetch_images\');  

    $post = get_post($post_ID);   

    $first_image = \'\';

    if(preg_match_all(\'/<img.+src=[\\\'"]([^\\\'"]+)[\\\'"].*>/i\', $post->post_content, $matches)){
        $first_image = $matches [1] [0];
    }

    if (strpos($first_image,$_SERVER[\'HTTP_HOST\'])===false)
    {

        //Fetch and Store the Image 
        $get = wp_remote_get( $first_image );
        $type = wp_remote_retrieve_header( $get, \'content-type\' );
        $mirror = wp_upload_bits(rawurldecode(basename( $first_image )), \'\', wp_remote_retrieve_body( $get ) );

        //Attachment options
        $attachment = array(
        \'post_title\'=> basename( $first_image ),
        \'post_mime_type\' => $type
        );

        // Add the image to your media library and set as featured image
        $attach_id = wp_insert_attachment( $attachment, $mirror[\'file\'], $post_ID );
        $attach_data = wp_generate_attachment_metadata( $attach_id, $first_image );
        wp_update_attachment_metadata( $attach_id, $attach_data );
        set_post_thumbnail( $post_ID, $attach_id );

        $updated = str_replace($first_image, $mirror[\'url\'], $post->post_content);

        //Replace the image in the post
        wp_update_post(array(\'ID\' => $post_ID, \'post_content\' => $updated));

        // re-hook this function
        add_action(\'future_to_publish\', \'fetch_images\', 10, 1);     
    }
}
?>
任何人都可以帮助修复此代码吗?

1 个回复
SO网友:Leandro Papasidero

使用transition_post_status 相反参考号:https://codex.wordpress.org/Post_Status_Transitions

结束

相关推荐

Host images only on CDN

我开发了一个wordpress网站,该网站托管在AWS上。该网站运行良好,但由于我希望它成为一个电子商务网站,将有大量的图像。AWS的托管帐户仅提供30 GB的存储空间。所以我想host images completely on an external CDN off my server. 但最近对CDN的搜索导致我只缓存CDN,我希望只在其他服务器上托管图像。有线索吗?