Add/Upload WordPress Feature image by Python
To add or upload a featured image to a WordPress post using Python, you will need to use the WordPress XML-RPC API. You can use a library such as python-wordpress-xmlrpc to interact with the API.
Here’s an example of how you could use the library to upload a featured image to a WordPress post:
from wordpress_xmlrpc import Client, WordPressPost from wordpress_xmlrpc.methods.media import UploadFile # Connect to WordPress wp = Client('http://yourwebsite.com/xmlrpc.php', 'username', 'password') # Prepare the image file for upload with open('image.jpg', 'rb') as img: data = { 'name': 'image.jpg', 'type': 'image/jpeg', 'bits': img.read(), } # Upload the image response = wp.call(UploadFile(data)) # Get the ID of the uploaded image image_id = response['id'] # Create a new post post = WordPressPost() post.title = 'My New Post' post.content = 'This is the content of my new post' post.thumbnail = image_id post.post_status = 'publish' # Publish the post wp.call(NewPost(post))
This is an example of how you can add/upload a featured image by Python. You can customize it according to your requirement.
Best method
To add or upload a featured image to a WordPress post using Python and an authentication token in the header, you will need to use the WordPress REST API. You can use a library such as requests to interact with the API.
Here’s an example of how you could use the requests library to upload a featured image to a WordPress post:
import requests import json # Set the endpoint for the REST API endpoint = 'http://yourwebsite.com/wp-json/wp/v2/media' # Prepare the image file for upload image = open('image.jpg', 'rb') # Set the headers for the request headers = { 'Authorization': 'Bearer YOUR_TOKEN_HERE', 'Content-Disposition': 'attachment; filename=image.jpg', 'Content-Type': 'image/jpeg' } # Send the request to upload the image response = requests.post(endpoint, headers=headers, data=image) # Get the ID of the uploaded image image_id = response.json()['id'] # Create a new post data = { 'title': 'My New Post', 'content': 'This is the content of my new post', 'featured_media': image_id, 'status': 'publish' } # Set the headers for the request headers = { 'Authorization': 'Bearer YOUR_TOKEN_HERE', 'Content-Type': 'application/json' } # Send the request to create the post response = requests.post('http://yourwebsite.com/wp-json/wp/v2/posts', headers=headers, json=data)
This is an example of how you can add/upload a featured image by Python using an authentication token in the header. You will need to replace “YOUR_TOKEN_HERE” with your authentication token and also update the endpoint to match your website.
You should also note that this example assumes that you have the necessary permissions and that the WordPress REST API is active on your website.
Add/Upload WordPress Feature image by Python
import requests from urllib.parse import urljoin import os import json import pandas as pd import csv from csv import writer from PIL import Image import base64 import cloudscraper scraper = cloudscraper.create_scraper() # wp app user & pass code-------------------- website_name = "piphones.net" Username = "Asrafulporag" App_pass = "wc2s 2Lig X48X 0uv8 Kb7L 0Jr5a" # WordPress posting code--------------------- json_url = 'https://'+website_name + '/wp-json/wp/v2' token = base64.standard_b64encode((Username + ':' + App_pass).encode('utf-8')) # we have to encode the usr and pw headers = {'Authorization': 'Basic ' + token.decode('utf-8')} # keyword = input("Enter your keyword: ") keyword = 'শ আ' # Uploading Img for post body image --------- media = {'file': open(keyword + '.jpg', 'rb')} # media = {'file': open('img/' + keyword + '.jpg', 'rb')} image = scraper.post(json_url + '/media', headers=headers, files=media) post_id = str(json.loads(image.content.decode('utf-8'))['id']) source = json.loads(image.content.decode('utf-8'))['guid']['rendered'] image_title = keyword.replace('-', ' ').split('.')[0] image1 = '<!-- wp:image {"align":"center","id":' + post_id + ',"sizeSlug":"full","linkDestination":"none"} -->' image2 = '<div class="wp-block-image"><figure class="aligncenter size-full"><img src="' + source + '" alt="' + image_title + '" title="' + image_title + '" class="wp-image-' + post_id + '"/></figure></div>' image3 = '<!-- /wp:image -->' image_wp = image1 + image2 + image3 # Feature image------------------------------ feature_image = image_wp imgurl_raw = feature_image.split('id":')[1] img_id = imgurl_raw.split(',')[0] # It will go under a Loop while keyword reading title = 'keyword' slug_keywords = 'keyword'.replace(' ', '-') post_body = 'post_body' # category_id = create_category('keyword') # tag_id = create_tag('keyword') status = "draft" # publish # draft post = {'title': title, 'slug': slug_keywords, 'status': status, 'content': post_body, # 'categories': [category_id], # 'tags': [tag_id], 'format': 'standard', 'featured_media': int(img_id), } # Posting Request--------------------------- r = scraper.post(json_url + '/posts', headers=headers, json=post) if r.status_code == 201: print('https://' + website_name + '/' + keyword.replace(' ', '-') + ' Has Been Posted') else: print(r.status_code,'error')
x
import os import json import base64 import cloudscraper scraper = cloudscraper.create_scraper() website_name = "piphones.net" Username = "Asrafulporag" App_pass = "wc2s 2Lig X48X 0uv8 Kb7L 0Jr5a" category = "Your Category Name" tags = "Tag Name" status = "draft" # publish # WordPress posting code----------------- json_url = 'https://'+website_name + '/wp-json/wp/v2' token = base64.standard_b64encode((Username + ':' + App_pass).encode('utf-8')) # we have to encode the usr and pw headers = {'Authorization': 'Basic ' + token.decode('utf-8')} # keyword = input("Enter your keyword: ") keyword = 'image' # Uploading Img for post body image def image_operation(keyword): try: media = {'file': open('img/' + keyword + '.jpg', 'rb')} image = scraper.post(json_url + '/media', headers=headers, files=media) image_title = keyword.replace('-', ' ').split('.')[0] post_id = str(json.loads(image.content.decode('utf-8'))['id']) source = json.loads(image.content.decode('utf-8'))['guid']['rendered'] image1 = '<!-- wp:image {"align":"center","id":' + post_id + ',"sizeSlug":"full","linkDestination":"none"} -->' image2 = '<div class="wp-block-image"><figure class="aligncenter size-full"><img src="' + source + '" alt="' + image_title + '" title="' + image_title + '" class="wp-image-' + post_id + '"/></figure></div>' image3 = '<!-- /wp:image -->' image_wp = image1 + image2 + image3 return image_wp except: return '' # Creating Tag def create_tag(tag_name): id = 0 data = {"name":tag_name} try: tag = scraper.post(json_url + '/tags', headers=headers, json=data) id = str(json.loads(tag.content.decode('utf-8'))['id']) except KeyError: tag = scraper.get(json_url + '/tags', headers=headers) tag_id = json.loads(tag.content.decode('utf-8')) for tag in tag_id: if tag_name.lower() in tag['name'].lower(): id = str(tag['id']) return id # Creating Category def create_category(cat_name): id = 0 data = {"name":cat_name} try: cat = scraper.post(json_url + '/categories', headers=headers, json=data) id = str(json.loads(cat.content.decode('utf-8'))['id']) except KeyError: cat = scraper.get(json_url + '/categories', headers=headers) cat_id = json.loads(cat.content.decode('utf-8')) for cat in cat_id: if cat_name.lower() in cat['name'].lower(): id = str(cat['id']) return id # Feature image def feature_image(keyword): try: feature_image = image_operation(keyword) imgurl_raw = feature_image.split('id":')[1] img_id = imgurl_raw.split(',')[0] return int(img_id) except: return 0 # It will go under a Loop while keyword reading title = 'keyword' keyword = 'keyword'.replace(' ', '-') post_body = 'post_body' category_id = create_category('keyword') tag_id = create_tag('keyword') img_id = feature_image('keyword') post = {'title': title, 'slug': keyword, 'status': status, 'content': post_body, 'categories': [category_id], 'tags': [tag_id], 'format': 'standard', 'featured_media': int(img_id), } # Posting Request r = scraper.post(json_url + '/posts', headers=headers, json=post) if r.status_code == 201: print('https://' + website_name + '/' + keyword.replace(' ', '-') + ' Has Been Posted') else: print(r.status_code,'error')
c
import requests from urllib.parse import urljoin import os import json import pandas as pd import csv from csv import writer from PIL import Image def list_to_row(filename, list_elements): with open(filename, 'a+', newline='', encoding='utf-8') as write_obj: csv_writer = writer(write_obj) csv_writer.writerow(list_elements) url_base = 'https://vehiclebd.com/' url = urljoin(url_base, 'wp-json/wp/v2/media/') user = 'Asrafulporag' password = '9qqX ILHq NJKL 9q1S pp3h GZtsa' # data = pd.read_csv("source/content.csv") # filename = data["Title"].replace(" ","-") f = open(r'001 humayun All1.csv', 'r', encoding='utf-8') reader = csv.reader(f) datas ={} i=1 for columns in reader: datas[i] = { 'image_urls': columns[4], } i = i+1 f.close() selected_post = input('Enter Number rang (1-11): ') numbers = selected_post.split('-') num1, num2 = int(numbers[0]), int(numbers[1]) for number in list(range(num1, num2)): single = datas[number] urli = single['image_urls'] # url = 'https://m.media-amazon.com/images/I/71FEJtVJQKS._AC_SL1500_.jpg' filename = urli.split('/')[-1]\ # .replace("jpeg", "jpg") f = open(f"Images copy/{filename}", "rb") image_data = f.read() f.close() # f = open("class-twoqaq.png", 'rb') # image_data = f.read() # f.close() # image_name = row["Spanish Title"].lower().replace(" ", "-") # filename = url.split('/')[-1] # filename = 'class-twoqaq.png' # print(filename) headers = { 'Content-Type': 'image/png', 'Content-Disposition': 'attachment; filename=' + filename, } res = requests.post( url, data=image_data, headers=headers, auth=(user, password), ) res_dict = res.json() # print(json.dumps(res_dict, indent=4)) unique_id = res_dict['id'] fileofurl = res_dict['source_url'] generated_slug = res_dict['generated_slug'] print(unique_id) print(fileofurl) print(generated_slug) final_list = [fileofurl, unique_id, generated_slug, ] list_to_row('00 All final unique ids.csv', final_list)