前言介紹
- 這款 WordPress 外掛「wp_wpcat_json_rest」是 2020-12-18 上架。
- 目前有 50 個安裝啟用數。
- 上一次更新是 2024-11-16,距離現在已有 169 天。
- 外掛最低要求 WordPress 6.2 以上版本才可以安裝。
- 外掛要求網站主機運作至少需要 PHP 版本 7.4 以上。
- 尚未有人給過這款外掛評分。
- 還沒有人在論壇上發問,可能目前使用數不多,還沒有什麼大問題。
外掛協作開發者
外掛標籤
api | JSON | rest | image | media library |
內容簡介
e Endpoint
The plugin provides the following endpoints for working with the Media-Library:
- GET /wp-json/wp/v2/media: Retrieve all images in the Media-Library with additional fields
- GET /wp-json/wp/v2/media/{id}: Retrieve a single image with additional fields
- POST /wp-json/rest-media-library/v1/media: Add a new image to the Media-Library with additional metadata and folder organization
- POST /wp-json/rest-media-library/v1/media/{id}: Update an existing image in the Media-Library with additional metadata and folder organization
- DELETE /wp-json/rest-media-library/v1/media/{id}: Delete a single image from the Media-Library. Only can be done with authorization.
Please note that authorization is required for all requests to these endpoints.
授權 (Authorization)
使用此外掛程式,所有對 WordPress REST-API 給予的請求皆需要在 HTTPS 頁首中呈現授權方式。使用 REST-API 進行數據讀取已不再被允許。以下是不同的授權方式:
使用 WP-Admin 帳號和密碼 + 使用者名稱 + Basic-Auth
此外掛程式不會提供這個功能, 若要使用 Basic-Auth,請採用其它外掛程式,並且應該配合使用 HTTPS 連線,不能使用 HTTP 連線。否則,您的管理員帳號和密碼將會暴露在網路中。
使用 WP REST 驗證碼 + Basic-Auth
這個功能只適用於 WordPress 5.6 版本以上,並且只能在已啟用 HTTPS 的網頁中使用。如果您的網站使用 HTTPS,則可以優先考慮使用這個授權方式。此外,須注意這個功能若搭配 HTTP 設定使用的話,並不建議這麼做。
使用步驟如下:
登入您的 WordPress 網站
前往管理後台 > 使用者 > 個人檔案
往下滾動到「應用程式密碼」項目
在欄位下方提供有用的名稱
點擊「新增新的應用程式密碼」按鈕
新的密碼將會出現,立即複製密碼並進行儲存!這個密碼不會再次顯示且請注意移除密碼之中的空格。
在 HTTPS 頁首中使用管理員的使用者名稱和新生成的應用程式密碼存取 WordPress 功能。
OAuth2
使用現存的 OAuth2 外掛程式進行驗證程序,這是比其他授權方式相對更安全更好的方法,但在應用程式端進行實作,會比較複雜且費時。
使用方式 (Endpoints 和 REST-API 欄位詳細說明)
REST-API 欄位
以下是透過 REST-API 取得的附加欄位:
- https://www.example.com/wp-json/wp/v2/media:取得 Media-Library 中的所有圖片以及額外的欄位。
- https://www.example.com/wp-json/wp/v2/media/{id}:取得單一圖片及其附加欄位。
- POST /wp-json/rest-media-library/v1/media:新增一個圖片到 Media-Library 中以及新增更多的圖片 metadata 和 folder organization
- POST /wp-json/rest-media-library/v1/media/{id}: 更新 Media-Library 中現有的圖片以及新增 metadata and folder organization。
- DELETE /wp-json/rest-media-library/v1/media/{id}:刪除 Media-Library 中一張圖片。需要授權才能進行刪除。
注意: 所有這些端點的請求皆需要經過授權。
原文外掛簡介
Extend the REST-API to work with WordPress Media-Library. Organize images in Folders. Add and Update images including Metadata and Posts using the images. Access with Authorization only.
This plugin extends the REST-API of WordPress to directly access the Media-Library for Images. It is intended to be used together with a Lightroom Plugin or as a stand-alone interface for headless WordPress. The new REST-API endpoints (functions) allow to add additional metadata to images, update existing metadata or update images completely without changing the WordPress-ID. Images may be added to the standard directory hierarchy of wordpress or to an additional folder which allows better organization and searching for images.
Authorization
With this plugin ALL requests to the REST-API of wordpress require an authorization method in the https-header. It is no longer possible to even read data via the REST-API. There are different authorization methods:
Use your WP-Admin Username and Password + username + Basic-Auth
This function is not provided by this plugin. There are plugins that allow Basic-Auth. It works fine with https. Never use it together with http. Your administrator username and password will be submitted to the internet.
Use WP REST application password + Basic auth
This works only with wordpress 5.6+ and may be used together with Basic-Auth. The setting is only provided if your website runs with https. So, use it only together with https (see above). I prefer this method and recommend to update to at least WP 5.6. There is a setting to use this method together with http, but this is not recommended.
Process:
Login to your wordpress-site
Go to Admin-Panel > User > Profile
Scroll down to “Application Passwords”
Provide a useful name for the application in the field underneath
Click the button “add new application password”
The new password will be shown. Copy it immediately and store it! It won’t be shown again. Remove the spaces from the password.
Use the username of the admin and the new generated password in the https-header to access to wordpress
OAuth2
Use existing plugins for the OAuth2 process. Best security compared to the other methods but very complicated to implement on the application side.
Usage (detailed list of endpoints and REST-API-fields)
REST-API-fields
The additional fields are available with the standard REST-API Endpoint: https://www.example.com/wp-json/wp/v2/media
1.1 Field ‘gallery’
This field may be used to organize images in galleries. The wordpress standard Media-Library does not provide a sorting scheme to organize images in galleries or topics. So -provided the gallery-plugin supports it- this is a simple way to organize images. Together with the plugin ‘AdvancedCustomFields’ it is possible to search for this field (or others).
1.2 Field ‘gallery_sort’
This field may be used for custom sorting of images shown in an image-slider or gallery. Only Integer values are allowed. Only useable with a plugin that supports this.
See for instance: https://github.com/MartinvonBerg/Fotorama-Leaflet-Elevation.
1.3 Field ‘md5_original_file’
This is an array that provides the MD5-hash-value (checksum) and the file size of the original image file. This data is used for the update process to check prior to the upload whether an image was changed or not. It’s intention is to reduce network load during update process.
1.4 Example JSON-snippet of the REST-API output for the above mentioned fields
“gallery”: “Albums”,
“gallery_sort”: “16”,
“md5_original_file”: {
“MD5”: “FCB639BB8191716A829F7B007056945B”,
“size”: 509168
},
How to get this: Open you browser and type https://www.your-domain.whatever/wp-json/wp/v2/media. Use Firefox to get a formatted output of the response. You have to be logged in to get the response.
1.5 How to write the fields:
Writing the fields is only possible with authorization. So, check the ‘authorization’ section before. This may be tested with ‘postman’, a great software for testing http(s)-requests.
Example https-request with POST-method:
https://www.your-domain.whatever/wp-json/wp/v2/media/666?gallery=test-gallery
New functionality behind this request
A POST-request with ‘alt_text’ and / or ‘caption’ will change the content of ALL posts using that image. The ‘alt_text’ and the ‘caption’ are updated if they are used in
gutenberg blocks ‘image’, ‘gallery’ and ‘media-with-text’. Note: There are many, many other blocks, images, galleries around. For these I couldn’t realize the update of ‘alt-text’ and ‘caption’.
New Parameter for the above POST-request
Add ?docaption=true to the http request and update ALL captions in the content, too. The ‘alt_text’ is always changed in the content, because IMO there could be only one alt_text for an image.
But, the caption may depend on the context, so it is up to the user, to change it automatically for all posts or not.
Mind: It is NOT required to use quotes around the value (here: test-gallery). If you use quotes, they will be used as part of the string in the field gallery.
1.6 Note on REST-API output
It is possible to reduce the REST-API output to dedicated fields. This is much better for overview and reducing net-load.
Example:
The https GET-Request
‘https://example.com/wp-json/wp/v2/media/?_fields=id,gallery’
provides this response:
[
{
“id”: 5013,
“gallery”: “Albums4”
},
{
“id”: 5012,
“gallery”: “Albums4”
},
{
“id”: 5011,
“gallery”: “Foto_Albums/Albums3”
},
{
“id”: 4932,
“gallery”: “Foto_Albums/Franken-Dennenlohe”
},
{
“id”: 4930,
“gallery”: “Foto_Albums/Franken-Dennenlohe”
},
{
“id”: 4929,
“gallery”: “Foto_Albums/Franken-Dennenlohe”
},
{
“id”: 4928,
“gallery”: “Foto_Albums/Franken-Dennenlohe”
},
{
“id”: 4927,
“gallery”: “Foto_Albums/Franken-Dennenlohe”
},
{
“id”: 4926,
“gallery”: “Foto_Albums/Franken-Dennenlohe”
},
{
“id”: 4925,
“gallery”: “Foto_Albums/Franken-Dennenlohe”
}
]
New REST-API-Endpoints (aka functions)
2.1 extmedialib/v1/update/(?P[\d]+)
Function to update images. Only integer values will be accepted for the ‘id’.
2.1.1 GET-method to extmedialib/v1/update/(?P[\d]+)
This function is just there for completeness. It provides some information for an existing image. The response to a GET-method to …/wp-json/extmedialib/v1/update/ is the following:
{
"message": "You requested update of original Image with ID 5013 with GET-Method. Please update with POST-Method.",
"original-file": "C:\\Bitnami\\wordpress-5.2.2-0\\apps\\wordpress\\htdocs/wp-content/uploads/Albums4/Friaul_2019_10-169_DxO.jpg",
"md5_original_file": "01CE0E6A16954C87586E9BF16044FDA0",
"max_upload_size": "41943040 bytes"
}
If the given wordpress-id does not exist it returns with http status-code 404.
2.1.2 POST-method to extmedialib/v1/update/(?P[\d]+)
This function updates the complete image including metadata. The given wordpress-id remains unchanged. Only the image-files that belong to that wordpress-id will be updated. All image sub-sizes will be regenerated. All metadata will be updated according to the EXIF-data in the provided image. To complete the update process it is required to set the fields ‘title’, ‘caption’, ‘alt_text’ and ‘description’ with the standard REST-API-methods (see above). The function ‘update_meta’ is included.
Note on image resizing: WordPress sets the standard resize quality to 82%. A setting of 100% was tested but with that the image-files were rather big.
The setting may be changed in the PHP-code only. Up to now there is now administration panel for the settings of this plugin. A programatical setting was added for that in version 0.0.18.
Note on image size: WordPress scales all images with pixel length (long side) greater than 2560 pixels down to this size. The bigger images will be stored in the ../uploads-directory but NOT used for the wordpress pages. So, it is not useful to upload images bigger than 2560 pixels. This may be changed by setting the ‘big_image_size_threshold’ by a dedicated hook. This is out of scope of this plugin.
Header for POST-method
To define the content-type the following fields have to be added to the header:
{field=’Content-Disposition’, value=’form-data; filename=
{field=’Content-Type’, value=’image/jpeg’},
OR
{field=’Content-Type’, value=’image/webp’},
Body for POST-method
The new Webp- or JPG-file has to be provided in the body as binary string. Checks in mime-type and size are done to prevent the user from uploading wrong data.
New Parameter for the POST-request
Add ‘?changemime=true to the http request and update the file with one that does have another mime-type.
2.2 extmedialib/v1/update_meta/(?P[\d]+)
Function to update metadata of images. Only integer values will be accepted for the id.
2.2.1 GET-method to extmedialib/v1/update_meta/(?P[\d]+)
This function is just there for completeness.
The response to a GET-method to ‘…/wp-json/extmedialib/v1/update_meta/wordpress-id’ is not executed. It may be used to check whether the image with the given wordpress-id is available. The response provides the http-status-code 405, if so. This could be done with a standard REST-request, too.
2.2.2 POST-method to extmedialib/v1/update_meta/(?P[\d]+)
This function updates the metadata of an existing image. It does not access the metadata that may be easily changed with the standard REST-API methods of wordpress (see there). It is only done if the ‘wordpress-id’ is a valid image and was added to the media-library before. For Jpegs it does NOT change ‘aperture, camera, created_timestamp, focal_length, iso, shutter_speed and orientation’. It is not very useful to change this data for an existing jpg-image. As the data is NOT set by WP for webp-images it is possible to add this data for Webp-Images now. The update or addition is done with a valid JSON-body and the respective settings in the http-header.
Header for POST-method
To define the content-type the following fields have to be added to the header:
{field=’Content-Type’, value=’application/json’}
Example Body for POST-method
The JSON has to be formatted like that:
{
“image_meta”: {
“credit”: “Martin von Berg”,
“caption”: “Test-caption”,
“copyright”: “Copyright by Martin von Berg”,
“title”: “Auffahrt zum Vallone d`Urtier”,
“keywords”: [
“Aosta”,
“Aostatal”,
“Berge”,
“Bike”,
“Italien”,
“Sommer”,
“Wald”,
“Wiese”,
“forest”,
“italy”,
“lärche”,
“meadow”,
“mountains”,
“summer”
]
}
}
All fields that are provided in the JSON will be changed. Empty fields will reset the content to an empty string “”.
2.3 extmedialib/v1/addtofolder/(?P[a-zA-Z0-9\/\-_]*)
This function stores images aside the wordpress standard folders but make them available in the media-library by generating a new wordpress-id. The ‘folder’ must not contain other characters than a-z, A-Z, 0-9, _ and -.
2.3.1 GET-method to extmedialib/v1/addtofolder/(?P[a-zA-Z0-9\/\-_]*)
This function is just there for completeness and simple checking. The response to a GET-method to ‘…/wp-json/extmedialib/v1/addtofolder/foldername’ simply gives the information whether the folder already exists or not.
2.3.2 POST-method to extmedialib/v1/addtofolder/(?P[a-zA-Z0-9\/\-_]*)
With the POST-method an image will be added to the given folder and with a new wordpress id. The response provides the new id and some basic information about the added image file.
Header for POST-method
To define the content-type the following fields have to be added to the header:
{field=’Content-Disposition’, value=’form-data; filename='
{field=’Content-Type’, value=’image/jpeg’},
OR
{field=’Content-Type’, value=’image/webp’},
Body for POST-method
The new JPG-file has to be provided in the body as binary string. Checks for mime-type and size are done to prevent the user from uploading wrong images.
2.4 extmedialib/v1/addfromfolder/(?P[a-zA-Z0-9\/\-_]*)
This function adds already uploaded images to the media-library. This is useful for images that were uploaded with ftp before. The ‘folder’ must not contain other characters than a-z, A-Z, 0-9, _ and -.
2.4.1 GET-method to extmedialib/v1/addfromfolder/(?P[a-zA-Z0-9\/\-_]*)
This method gives information about the folder content. If existing and not empty the folder content will be provided as an array. The array provides now the id’s and original-files that are already in the media-library.
2.4.2 POST-method to extmedialib/v1/addfromfolder/(?P[a-zA-Z0-9\/\-_]*)
With the POST-method all images from the given ‘folder’ will be added to the media-library. Image-Files that were already added before from THAT dedicated folder will be skipped. The response contains an JSON-array with IDs to be stored in the application (e.g. Lightroom) for later access. Mind that this might be a long running process. If it runs too long it will be stopped by the server and the addition is NOT complete. So, the recommendation is to do this step by step, e.g. 10 images maximum per step.
Tests
3.0 Linting with phpstan
Code quality was checked with phpstan and WP extensions ‘szepeviktor/phpstan-wordpress’ and ‘phpstan/extension-installer’.
Level 5 is OK except 19 remaining Errors. These were carefully reviewed and regarded as OK.
Command: php .\vendor\phpstan\phpstan\phpstan analyse classes inc .\wp_wpcat_json_rest.php –memory-limit 1G
3.1. Unit-Tests
Meaningful Unit-Tests are now done with PHPUnit. The files are located in ./tests.
3.2. Integration Test
Well, IMO this is mainly the (de-)installation procedure for the plugins. Tested manually. Works
3.3 System Test
The plugin is now ‘completely’ system tested with a new python test suite (PTS). The PTS uses pytest and a bunch of other python modules that have to be installed in the Python environment.
I tried to reach a ‘branch coverage’ of 100% concerning the functional branches. It’s almost impossible to test the paths that were implemented for very special
errors on the server (domain of unit tests). The testdata contains *.webp and *.jpg files with different sizes. The use cases are ‘upload image file’, ‘change metadata’, ‘change mime type’,
‘update image file’, ‘create posts (Gutenberg: image, gallery, image-with-text )’ and ‘delete’. Tests were conducted on a local and remote site. Additionally I
checked the results of query monitor for every REST-request that uses a function from me. No PHP-errors at all. So, all tests passed. I could not
claim a code coverage of 100% or even a test coverage of 100%. That is almost impossible.
3.3.1 How to repeat the system test
– Install an empty, new WP site
– Install this plugin
– Install Query Monitor plugin
– Clone the complete code from github to your local site
– change the directory to the …./test directory in the cloned repository
– provide a wp_site.json as described in ./test/test_rest-api.py
– run the basic tests with: pytest -k ‘basic’
– The first run wil fail for one test if the required ‘testfolder’ did not exist on the server.
– Once more: run the basic tests with: pytest -k ‘basic’. should be 100% PASSED now.
– Check your WP-testsite and delete the generated image(s)
– run the full test with: pytest -k ‘testimage or testfield or testpost or cleanup’
– check the testreport.html after the test
– OR
– run the full test and stop it after the post generation with
– pytest -k ‘testimage or testfield or testpost or cleanup or testwait’ -s
– check visually that all posts with image, gallery, image-with-text have flipped images (except one with changed mime-type)
– continue the test with Enter to delete all generated images, posts etc. from WordPress
– OR run
– pytest -k ‘testimage or testfield or testpost’ –> here you have to delete all generated images, posts etc. from WordPress manually
– NOTE: Sometimes the test_clean_up() function does not delete all files in the ./testfolder on the server. Don’t know why.
– So it is better to check that folder ./testfolder is really empty if the test fails.
– Finally, all tests should be PASSED and GREEN.
Credits
This plugin uses the great work from:
wordpress for coding hints: https://de.wordpress.org/
authorization hints: https://developer.wordpress.org/rest-api/frequently-asked-questions/
Enable Media Replacer: https://de.wordpress.org/plugins/enable-media-replace/ I’m using two classes of this great plugin to handle the link updates.
PHPunit and BrainMonkey for Testing
各版本下載點
- 方法一:點下方版本號的連結下載 ZIP 檔案後,登入網站後台左側選單「外掛」的「安裝外掛」,然後選擇上方的「上傳外掛」,把下載回去的 ZIP 外掛打包檔案上傳上去安裝與啟用。
- 方法二:透過「安裝外掛」的畫面右方搜尋功能,搜尋外掛名稱「wp_wpcat_json_rest」來進行安裝。
(建議使用方法二,確保安裝的版本符合當前運作的 WordPress 環境。
0.1.0 | 0.1.2 | 0.1.3 | 0.1.4 | 0.1.5 | 1.0.0 | 1.1.0 | trunk | 0.0.15 | 0.0.16 | 0.0.17 | 0.0.18 | 0.0.19 |
延伸相關外掛(你可能也想知道)
Image Optimization by Optimole – Lazy Load, CDN, Convert WebP & AVIF, Optimize Images 》, Optimole的獨特之處在哪裡?, , 更小的圖片,同樣的品質, 完全自動化;設定一次就忘記它, 支援所有圖片格式, 支援Retina和WebP圖片, 以機器學習為基礎的自...。
Imsanity 》使用 Imsanity,自動調整大型圖片上傳大小。選擇你喜歡的尺寸和品質,讓 Imsanity 完成其餘所有工作。當投稿者上傳大於配置尺寸的圖片時,Imsanity 將自動將...。
Firelight Lightbox 》Easy FancyBox WordPress外掛為您的網站提供靈活美觀的光箱解決方案,幾乎適用於網站上的所有媒體連結。Easy FancyBox使用更新的傳統FancyBox jQuery擴展版本...。
Simple Lightbox 》Simple Lightbox 是一個非常簡單且可自定義的燈箱,在您的 WordPress 網站上添加它非常容易。, 功能, 自定義燈箱行為的選項位於外觀 > Lightbox 管理員菜...。
Robin image optimizer — save money on image compression 》需要專業支援嗎?, 開始免費支援, 開始高級支援, 透過減少圖像大小,讓您的網站加快速度。我們的 WordPress 圖像優化外掛,可以將圖像大小減少80%,而且不損...。
Responsive Lightbox & Gallery 》提供完整的 WordPress 相簿外掛所需一切, Responsive Lightbox and Gallery 外掛是一個全功能的 WordPress 相簿外掛,擁有強大的拖放相簿生成器和 Lightbox ...。
reSmush.it : The original free image compressor and optimizer plugin 》reSmush.it Image Optimizer 是一個 WordPress 外掛,透過 reSmush.it API 提供圖片優化服務。reSmush.it 使用多種高級演算法對圖像進行大小減小。API 支援最...。
Menu Image, Icons made easy 》這個外掛可以輕鬆地在選單項目中加入圖像或圖示,打造更好的網站選單。, 可以控制圖像或圖示的位置以及大小。, 這個 Menu Image 外掛還有其他功能,以下是其...。
Image Widget 》Image Widget 是一個簡單的外掛程式,利用 WordPress 原生媒體管理員,為您的網站新增圖片小工具。, 需要新增幻燈片、燈箱或隨機圖像嗎?, 請查看 Image Widg...。
Featured Image from URL (FIFU) 》h3>WordPress 外掛 - 用於顯示外部特色圖片、影片、音訊等等, FIFU 自 2015 年來已幫助全球數千個網站節省了儲存空間、處理時間和版權費用。, 如果您已經厭倦...。
Default Featured Image 》在媒體設定頁面上新增一個預設的特色圖像。如果沒有設定任何特色圖像,這個預設的特色圖像就會顯示。就這麼簡單。, 查看常見問題以獲取基本問題資訊。, 如果...。
All In One Favicon 》查看最新的WordPress交易以優化您的網站。, All In One Favicon為您的網站和管理頁面添加favicon。, 您可以使用您已經上傳的favicon或使用內置的上傳機制將fa...。
ImageMagick Engine 》透過讓 WordPress 使用 ImageMagick 而非標準的 GD 圖像庫,大幅提升重新調整大小的圖像品質。, 功能, , 在重新調整大小的圖像中保留嵌入式色彩設定檔, 自動...。
WP Featherlight – A Simple jQuery Lightbox 》WP Featherlight 是一個 WordPress 外掛,可為您的WordPress 網站添加一個極簡、高效、響應式 jQuery 燈箱。在其核心,WP Featherlight是一個用於 Featherlig...。
Phoenix Media Rename 》通過使用「Phoenix Media Rename」外掛,將您的媒體檔案重新命名,極大地提高您的 SEO。, 在Phoenix Media Rename 官方頁面上提供了完整的使用和設置指南。。