如果发布了帖子,则下载外部图像

时间:2018-09-16 作者:Ruriko

我已经安排了包含外部图像的帖子。我希望它能自动下载图像&;如果发布状态为“发布”,则链接到媒体库。现在的问题是,当发布日程公告时,我的代码不会下载图像。如果您立即创建文章并发布,但对于以后转换为发布的明细表文章,则该方法不起作用。

有人能帮我修复代码吗?

<?php  
/*  
Plugin Name: Download External images
Version: 1.0
*/
add_action(\'publish_post\', \'fetch_images\');

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(\'publish_post\', \'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(\'publish_post\', \'fetch_images\');     
    }
}
?>

1 个回复
SO网友:janh

计划发布不会触发publish_post, 只有更新帖子本身才能做到这一点。

为添加操作future_to_publish, 请参见reference on post status transitions. 我认为在这种情况下,您无法访问user对象,因此您可能需要重构它。

或者,只在用户保存帖子时获取图像,而不是发布帖子时获取图像。使用save_post 行动

结束

相关推荐

NEXT_POSTS_LINK在首页不可见

我拿不到<?php next_posts_link(); ?> 在第一页(website.com/news)的自定义帖子循环中工作。有趣的是<?php previous_posts_link(); ?> 是否在第二页(website.com/news/page/2/)上工作这是我的问题:<div class=\"col-md-12\"> <h2>News</h2> <?php $pag