如何将mp3从url上传到wp媒体

时间:2019-12-08 作者:Chinemerem Alozie

您好,我正在尝试修改此插件以支持从url上传mp3

<?php
/*

*/



        add_filter("media_upload_tabs",array(&$this,"build_tab"));
        add_action("media_upload_grabAndSave", array(&$this, "menu_handle"));
    }

    /*
     * Merge an array into middle of another array
     *
     * @param array $array the array to insert
     * @param array $insert array to be inserted
     * @param int $position index of array
     */
    function array_insert(&$array, $insert, $position) {
        settype($array, "array");
        settype($insert, "array");
        settype($position, "int");

        //if pos is start, just merge them
        if($position==0) {
            $array = array_merge($insert, $array);
        } else {


            //if pos is end just merge them
            if($position >= (count($array)-1)) {
                $array = array_merge($array, $insert);
            } else {
                //split into head and tail, then merge head+inserted bit+tail
                $head = array_slice($array, 0, $position);
                $tail = array_slice($array, $position);
                $array = array_merge($head, $insert, $tail);
            }
        }
        return $array;
    }


    function build_tab($tabs) {
        $newtab = array(\'grabAndSave\' => __(\'Grab & Save\', \'grabAndSave\'));
        return $this->array_insert($tabs, $newtab, 2);
        //return array_merge($tabs,$newtab);
    }
    function menu_handle() {
        return wp_iframe(array($this,"media_process"));
    }
    function fetch_image($url) {
        if ( function_exists("curl_init") ) {
            return $this->curl_fetch_image($url);
        } elseif ( ini_get("allow_url_fopen") ) {
            return $this->fopen_fetch_image($url);
        }
    }
    function curl_fetch_image($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $image = curl_exec($ch);
        curl_close($ch);
        return $image;
    }
    function fopen_fetch_image($url) {
        $image = file_get_contents($url, false, $context);
        return $image;
    }

    function media_process() {

        if ( $_POST[\'imageurl\'] ) {
            $imageurl = $_POST[\'imageurl\'];
            $imageurl = stripslashes($imageurl);
            $uploads = wp_upload_dir();
            $post_id = isset($_GET[\'post_id\'])? (int) $_GET[\'post_id\'] : 0;
            $ext = pathinfo( basename($imageurl) , PATHINFO_EXTENSION);
            $newfilename = $_POST[\'newfilename\'] ? $_POST[\'newfilename\'] . "." . $ext : basename($imageurl);

            $filename = wp_unique_filename( $uploads[\'path\'], $newfilename, $unique_filename_callback = null );
            $wp_filetype = wp_check_filetype($filename, null );
            $fullpathfilename = $uploads[\'path\'] . "/" . $filename;

            try {
                if ( !substr_count($wp_filetype[\'type\'], "image") ) {
                    throw new Exception( basename($imageurl) . \' is not a valid image. \' . $wp_filetype[\'type\']  . \'\' );
                }

                $image_string = $this->fetch_image($imageurl);
                $fileSaved = file_put_contents($uploads[\'path\'] . "/" . $filename, $image_string);
                if ( !$fileSaved ) {
                    throw new Exception("The file cannot be saved.");
                }

                $attachment = array(
                     \'post_mime_type\' => $wp_filetype[\'type\'],
                     \'post_title\' => preg_replace(\'/\\.[^.]+$/\', \'\', $filename),
                     \'post_content\' => \'\',
                     \'post_status\' => \'inherit\',
                     \'guid\' => $uploads[\'url\'] . "/" . $filename
                );
                $attach_id = wp_insert_attachment( $attachment, $fullpathfilename, $post_id );
                if ( !$attach_id ) {
                    throw new Exception("Failed to save record into database.");
                }
                require_once(ABSPATH . "wp-admin" . \'/includes/image.php\');
                $attach_data = wp_generate_attachment_metadata( $attach_id, $fullpathfilename );
                wp_update_attachment_metadata( $attach_id,  $attach_data );

            } catch (Exception $e) {
                $error = \'<div id="message" class="error"><p>\' . $e->getMessage() . \'</p></div>\';
            }

        }
        media_upload_header();
        if ( !function_exists("curl_init") && !ini_get("allow_url_fopen") ) {
            echo \'<div id="message" class="error"><p><b>cURL</b> or <b>allow_url_fopen</b> needs to be enabled. Please consult your server Administrator.</p></div>\';
        } elseif ( $error ) {
            echo $error;
        } else {
            if ( $fileSaved && $attach_id ) {
                echo \'<div id="message" class="updated"><p>File saved.</p></div>\';
            }
        }
        ?>
        <form action="" method="post" id="image-form" class="media-upload-form type-form">
        <h3 clas s="media-title">Grab Image from URL</h3>
        <div class="describe">Image URL: 
        <input id="src" type="text" name="imageurl"><br/>
        Save as (optional) <input type="text" name="newfilename" style="width:200px">
        <input type="submit" class="button" value="Grab">
        </div>

        </form>
        <?php

        if ( $attach_id )  {
            $this->media_upload_type_form("image", $errors, $attach_id);
        }
        ?>
        <div style="padding:10px;"><a href="http://digitalmemo.neobie.net/grab-save/" target="digitalmemo" style="text-decoration:none;font-size:0.8em;">&copy; neobie @ DigitalMemo</a>
        <br/><a href="http://digitalmemo.neobie.net/donate" target="_blank"><img src="https://www.paypal.com/en_US/i/btn/btn_donate_SM.gif"></a>
        </div>
        <?php
    }


    /*
     * modification from media.php function
     *
     * @param unknown_type $type
     * @param unknown_type $errors
     * @param unknown_type $id
     */
    function media_upload_type_form($type = \'file\', $errors = null, $id = null) {

        $post_id = isset( $_REQUEST[\'post_id\'] )? intval( $_REQUEST[\'post_id\'] ) : 0;

        $form_action_url = admin_url("media-upload.php?type=$type&tab=type&post_id=$post_id");
        $form_action_url = apply_filters(\'media_upload_form_url\', $form_action_url, $type);
        ?>

        <form enctype="multipart/form-data" method="post" action="<?php echo esc_attr($form_action_url); ?>" class="media-upload-form type-form validate" id="<?php echo $type; ?>-form">
        <input type="submit" class="hidden" name="save" value="" />
        <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
        <?php wp_nonce_field(\'media-form\'); ?>

        <script type="text/javascript">
        //<![CDATA[
        jQuery(function($){
            var preloaded = $(".media-item.preloaded");
            if ( preloaded.length > 0 ) {
                preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, \'\')},\'\');});
            }
            updateMediaForm();
        });
        //]]>
        </script>
        <div id="media-items">
        <?php
        if ( $id ) {
            if ( !is_wp_error($id) ) {
                add_filter(\'attachment_fields_to_edit\', \'media_post_single_attachment_fields_to_edit\', 10, 2);
                echo get_media_items( $id, $errors );
            } else {
                echo \'<div id="media-upload-error">\'.esc_html($id->get_error_message()).\'</div>\';
                exit;
            }
        }
        ?>
        </div>
        <p class="savebutton ml-submit">
        <input type="submit" class="button" name="save" value="<?php esc_attr_e( \'Save all changes\' ); ?>" />
        </p>
        </form>

        <?php
    }
}

new GrabAndSave();
?>

1 个回复
最合适的回答,由SO网友:Chetan Vaghela 整理而成

正如@fuxia所建议的,您必须扩展$wp_filetype 同时检查mp3。对于mp3扩展,您可以使用audio/mpeg3, audio/x-mpeg-3, video/mpeg, video/x-mpeg mime类型。只需在中添加检查条件try 检查图像有效类型的块。我已经测试过了,对我来说效果很好。如果这对你有帮助,请告诉我。

if ( !substr_count($wp_filetype[\'type\'], "image") &&  !substr_count($wp_filetype[\'type\'], "audio")) {
    throw new Exception( basename($imageurl) . \' is not a valid \' . $wp_filetype[\'type\']  . \'\' );
}

相关推荐

Extra "uploads" added in path

虽然这与高级自定义字段相关,但此函数使用所有本机WP特性,因此我认为在这里询问这一点是合适的。路径中的额外“/上传/”来自何处?在后端,我看到了上传文件的正确链接(domain.com/wp-content/member-files/name.pdf),但在前端,URL在路径(domain.com/wp-content/uploads/member-files/name.pdf)中显示了额外的“/uploads/”,当然为文件生成了404。// file upload to custom location