Created
March 20, 2018 18:17
-
-
Save omiq/7d7116b823c6d8861e9c1e1e3d9ed871 to your computer and use it in GitHub Desktop.
Upload images to WordPress and copy web URL to clipboard
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import sys | |
| import os | |
| import requests | |
| import pyperclip | |
| # did the user supply an image file? | |
| if len(sys.argv) == 2: | |
| image = sys.argv[1] | |
| else: | |
| input("You must supply an image file!") | |
| exit() | |
| # get just the filename | |
| slug = os.path.basename(image) | |
| # this line needs to be changed to YOUR wp site | |
| url = "https://YOURWEBURL.com/wp-json/wp/v2/media/?title=" + slug | |
| # the headers for the request (right now hard coded to be PNG because that is all I need) | |
| headers = { | |
| 'Content-Type': "image/png", | |
| 'content-disposition': "attachment; filename=" + slug, | |
| 'Cache-Control': "no-cache", | |
| } | |
| # get the image file data | |
| file_data = open(image, 'rb') | |
| # set up the parameters - basic login details from the environment variables | |
| files = {'file': file_data} | |
| user = os.environ['WPUSER'] | |
| password = os.environ['WPPASS'] | |
| # send the data and get the response back | |
| response = requests.request( | |
| "POST", | |
| url, | |
| headers = headers, | |
| data = file_data, | |
| auth = (user, password)) | |
| # parse the response via the JSON library | |
| json = response.json() | |
| guid = json.get('guid') | |
| url = guid.get('raw') | |
| # display the generated image URL and copy | |
| # to clipboard. Should just work on mac/win | |
| # Ubuntu clipboard is pretty crap so you will need | |
| # xclip and Parcellite to make it usable | |
| print(url) | |
| pyperclip.copy(url) | |
| # I add this just so the window doesn't vanish | |
| # while testing, otherwise not needed | |
| end = input('Press Enter to Close') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment