WordPress开发常用函数(Function)方法

这篇来整理一下最近开发项目时,发现有不少可以复用的方法。

不全然都是使用 WordPress 内建提供的方法,有时候会是在非 WordPress 安装的环境验证算法与操作,效率更高。

之后有常用的方法就来更新这篇~

需要网络爬存数据(API请求)

function mxp_do_request(string $url, string $type = 'GET', array $headers = [], array $post_fields = [], string $user_agent = '', string $referrer = '', bool $follow = true, bool $use_ssl = false, int $con_timeout = 10, int $timeout = 40) {
    $crl = curl_init($url);
    curl_setopt($crl, CURLOPT_CUSTOMREQUEST, $type);
    curl_setopt($crl, CURLOPT_USERAGENT, $user_agent);
    curl_setopt($crl, CURLOPT_REFERER, $referrer);
    if ($type == 'POST') {
        curl_setopt($crl, CURLOPT_POST, true);
        if (!empty($post_fields)) {
            curl_setopt($crl, CURLOPT_POSTFIELDS, $post_fields);
        }
    }
    if (!empty($headers)) {
        curl_setopt($crl, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($crl, CURLOPT_FOLLOWLOCATION, $follow);
    curl_setopt($crl, CURLOPT_CONNECTTIMEOUT, $con_timeout);
    curl_setopt($crl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, $use_ssl);
    curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, $use_ssl);
    curl_setopt($crl, CURLOPT_ENCODING, 'gzip,deflate');
    curl_setopt($crl, CURLOPT_RETURNTRANSFER, true);
    $call_response = curl_exec($crl);
    curl_close($crl);
    return $call_response; //Return data
}

上面是PHP cURL实作的版本,下方则是套用WordPress内建方法的改版,同样参数,替换实作内容就可以无缝切入。

function mxp_do_request(string $url, string $type = 'GET', array $headers = [], array $post_fields = [], string $user_agent = '', string $referrer = '', bool $follow = true, bool $use_ssl = false, int $con_timeout = 10, int $timeout = 40) {
    $args = array(
        'method'      => $type,
        'timeout'     => $timeout,
        'redirection' => 5,
        'httpversion' => '1.1',
        'blocking'    => true,
        'sslverify'   => $use_ssl,
        'headers'     => [
            'User-Agent' => $user_agent,
            'Referer'    => $referrer,
        ],
        'body'        => $post_fields,
    );
    if (!empty($headers) && count($headers) != 0) {
        foreach ($headers as $key => $header) {
            $args['headers'][$key] = $header;
        }
    }
    $response = wp_remote_request($url, $args);
    $body     = wp_remote_retrieve_body($response);

    return $body;
}

下载文件

cURL 简易的下载文件方式,适用下载档案资源路径(URL)包含文件名称与档案类型(MIME Type)明确不带其他 Query String 的作法

function mxp_download_source($url, $name) {
    $name_path = $name;
    $suffix    = end(explode('.', $url));
    $file_name = dirname(__FILE__) . "/" . $name_path . "." . $suffix;
    if (file_exists($file_name)) {
        return $file_name;
    }
    $fp = fopen($file_name, 'w+');
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    $data = curl_exec($ch);
    curl_close($ch);
    fclose($fp);
    fputs($fp, $data);
    fclose($fp);
    return $file_name;
}

下载压缩格式的档案,并解压缩.gz

function mxp_download_source($url) {
    $path          = basename(parse_url($url, PHP_URL_PATH));
    $file_name     = dirname(__FILE__) . "/" . $path;
    $buffer_size   = 4096; // read 4kb at a time
    $out_file_name = str_replace('.gz', '', $file_name);
    if (file_exists($out_file_name)) {
        return $out_file_name;
    }
    $fp = fopen($file_name, 'w');
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    $data = curl_exec($ch);
    curl_close($ch);
    fclose($fp);
    $file     = gzopen($file_name, 'rb');
    $out_file = fopen($out_file_name, 'wb');
    while (!gzeof($file)) {
        fwrite($out_file, gzread($file, $buffer_size));
    }
    fclose($out_file);
    gzclose($file);
    unlink($file_name);
    return $out_file_name;
}

算文本文件总行数(适用大文件)

//https://stackoverflow.com/questions/2162497/efficiently-counting-the-number-of-lines-of-a-text-file-200mb
$file = new SplFileObject($source_file);
$file->seek(PHP_INT_MAX);
$total_lines = $file->key() + 1;

照行数读取文字档案内容

    $file        = new SplFileObject($filename);
    $line        = '';
    $file_number = get_total_lines($filename);
    $left_items  = $file_number % 5000;
    for ($i = 1; $i <= $file_number; ++$i) {
        if (!$file->eof()) {   
            //https://stackoverflow.com/questions/5775452/php-read-specific-line-from-file
            $file->seek($i);//帶入行號
            $line    = $file->current();//取得該行內容
        }
    }

下载远程图片并上传 WordPress 媒体库与加入文章精选图片

function mxp_download_and_insert_wp($link = '', $author_id = 1, $post_parent = 0, $att_title = '', $att_content = '', $set_post_thumbnail = true) {
    if ($link == '') {
        return false;
    }
    require_once ABSPATH . 'wp-admin/includes/media.php';
    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/image.php';
    $filename    = basename(parse_url($link, PHP_URL_PATH));
    $options     = array('timeout' => 300);
    $upload_file = null;
    $response    = wp_safe_remote_get($link, $options);
    if (!is_wp_error($response)) {
        $data        = wp_remote_retrieve_body($response);
        $upload_file = wp_upload_bits($filename, null, $data);
    } else {
        return false;
    }
    $wp_filetype = wp_check_filetype($filename, null);
    $attachment  = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_parent'    => $post_parent,
        'post_author'    => $author_id,
        'post_title'     => preg_replace('/\.[^.]+$/', '', $att_title),
        'post_content'   => $att_content,
        'post_status'    => 'inherit',
    );
    $attachment_id = wp_insert_attachment($attachment, $upload_file['file'], $post_parent);
    if (!is_wp_error($attachment_id)) {
        //產生附加檔案中繼資料
        $attachment_data = wp_generate_attachment_metadata($attachment_id, $upload_file['file']);
        wp_update_attachment_metadata($attachment_id, $attachment_data);
        //將圖像的附加檔案設為特色圖片
        $type = explode("/", $wp_filetype['type']);
        if ($set_post_thumbnail && $type[0] == 'image') {
            set_post_thumbnail($post_parent, $attachment_id);
        }
        return true;
    } else {
        return false;
    }
}

这个方法我这样写应该算是很 WordPress 的原生处理方式了,网络上还有其他网友分享的方法也可以参考: Gist: Upload an image to WordPress media gallery from URL

发表评论

您的电子邮箱地址不会被公开。