• Home
  • Bulk Create WordPress Categories using the REST API & Python

    Chris

    Administrator
    Staff member
    Are you developing a new WordPress project and planning to use categories? In this post, I will show you how to use the WordPress Rest API to bulk create WordPress categories.

    I will try to keep this article short and concise as the Python script will do the work

    Table of Contents​


    1, Import Libraries
    2, Connect to the WordPress Rest API
    3, Load your List of Categories
    4, Build the Category Schemas
    5, Run the Script
    6 Testing the Output


    Import Libraries​

    Import the following Python libraries. We need these libraries to successfully run and test the script output.
    Code:
    # Import modules
    import pandas as pd
    import requests
    import csv
    import json
    import base64
    from tqdm.notebook import tqdm


    Connect to the REST API​

    Replace the API credentials with your own credentials.

    Code:
    # WordPress Rest API credentials
    user = 'admin'
    password = 'mV22 tSqH Ytyx V0ZF zaNd NP9n' # freeze
    url = 'https://mydomain.com/wp-json/wp/v2'
    
    wp_connection = user + ':' + password
    token = base64.b64encode(wp_connection.encode())
    
    
    # Base64 Authentication WordPress
    headers = {'Authorization': 'Basic ' + token.decode('utf-8')}

    Load your list of Categories​

    Load in your local or remote CSV file containing the list of categories that you wish to create. To begin with, you only need the category ID and category name for this script to work. If you are going to create descriptions and custom slugs load that data. Use one column per schema. Read the WordPress handbook for schema names - https://developer.wordpress.org/rest-api/reference/categories/

    Code:
    # Paste your csv file name here - for example: sample-data.csv or remote link
    df = pd.read_csv("c:\data\terms5.csv")
    df

    Build the Category Schemas​

    Add or remove category schemas to suit your requirements. The minimum requirement is the category parent ID and category name.
    Code:
    # The minimum is category parent and category name
    def wp_cat_insert(parent_id, cat_name):
    
        post = {'parent': parent_id,
                'name': cat_name
                }
    
        wp_cat_insert_request = requests.post(url + '/categories', headers=headers, json=post)

    Run the Command​

    We are now on the final stage of the script. We need to execute the code. This next code snippet executes the script with progress status using the TQDM module.

    Code:
    # Executes the script and runs the TQDM progress bar
    for index, row in tqdm(df.iterrows()):
    
    # Add or remove WordPress category schemas variables below
        wp_cat_insert(row["parent_id"], row["cat_name"])

    Testing the Output​

    To test the script and see if the categories have been created via the API you can check in PHP Myadmin or create a new dataframe to fetch the list of categories. Word of warning you can only retrieve 100 rows in a single WordPress API call.
    Code:
    # Wordpress max row API call is 100 rows
    df = pd.read_json(
        "https://mydomain.com/wp-json/wp/v2/categories/?per_page=100")
    
    
    df = pd.DataFrame(df, columns = ['name', 'slug', 'parent', 'id', 'link'])
    with pd.option_context('display.max_rows', None, 'display.max_columns', None):
    
        display(df)
    
    # export dataframe to csv
     # df.to_csv(r'c:\categories.csv', index = False)

    pd1.jpg


    Wrapping it up​

    That's it - use the above python snippets to build the script in Jupyter Notebook or Google Colab. Comment below if you have any questions or suggestions to improve the script. I decided to write this bulk create WordPress categories as I'm currently working on a project that has many thousands of categories.

    pd2.jpg


    I have recently also written a Python tutorial to bulk create WordPress post via the REST API. Read it here - https://chrisleverseo.com/t/python-...-from-a-csv-file-using-wordpress-rest-api.93/

    Thanks for reading.
     
    Last edited: