• Home
  • About
  • Services
    • Technical SEO
    • Local SEO Services
  • Tools
    • Redirects Generator
    • HREFLANG Tag Generator
    • XML Sitemap Generator
    • XML Sitemap URL Extractor
    • Robots.txt Generator
    • Random URL Generator
    • Meta Robots Tag Generator
    • Organization Schema Generator
    • Article Schema Generator
    • Product Schema Generator
    • Local Business Schema Generator
    • FAQPage Schema Generator
    • WordPress Metabox Generator
    • Plugins & Scripts
  • Tutorials Hub
    • Technical SEO
    • WordPress
    • PHP
    • JavaScript
    • Python
    • Google Tag Manager
    • Shopify
    • Other Guides & Tutorials
    • General Discussion
    • View All
  • Contact
    • Hub
      New posts Search forums
    • What's new
      New posts New profile posts Latest activity
    • Members
      Current visitors New profile posts Search profile posts
    Log in Register
    What's new Search

    Search

    By:
    Advanced search…
    • New posts
    • Search forums
    Menu
    Log in

    Register

    Install the app
    • Home
      • Hub
      • Python Scripts & Tutorials
      You are using an out of date browser. It may not display this or other websites correctly.
      You should upgrade or use an alternative browser.

      Bulk Create WordPress Categories using the REST API & Python

      • Thread starter Chris
      • Start date Nov 3, 2022
      C

      Chris

      Administrator
      Staff member
      • Nov 3, 2022
      • #1
      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: Nov 3, 2022
      You must log in or register to reply here.
      Share:
      Facebook Twitter Reddit Pinterest Tumblr WhatsApp Email Share Link

      New Posts

      • C
        add a number to the next column of data, increasing the number as the datapoint changes, and count how many times each datapoint appears
        • Started by Chris
        • Jul 20, 2023
        • Replies: 0
        Other Plugins & Tutorials
      • C
        How to connect to GPT-4 API with Node.js using PowerShell
        • Started by Chris
        • Jul 14, 2023
        • Replies: 0
        JavaScript Scripts & Snippets
      • C
        Google Search Results Scraper - Node JS & Puppeteer
        • Started by Chris
        • Jul 2, 2023
        • Replies: 0
        JavaScript Scripts & Snippets
      • C
        Detect unused JavaScript and CSS in Bulk
        • Started by Chris
        • Jun 29, 2023
        • Replies: 0
        JavaScript Scripts & Snippets
      • C
        Google Sheets Apps Script to Generate Hreflang tags
        • Started by Chris
        • Jun 12, 2023
        • Replies: 0
        Technical SEO
      • C
        Deploying Noindex Meta Robots Tag with JavaScript with Tag Manager - 2 Methods
        • Started by Chris
        • Jun 9, 2023
        • Replies: 0
        Google Tag Manager Tutorials & Guides
      • C
        Guide to Google Search Operators
        • Started by Chris
        • Jun 9, 2023
        • Replies: 0
        Other Plugins & Tutorials
      • C
        Bookmarklet to inspect and identify images that are not using lazy loading on a webpage
        • Started by Chris
        • Jun 2, 2023
        • Replies: 0
        JavaScript Scripts & Snippets
      • Hub
      • Python Scripts & Tutorials

    Technical SEO Consultant

    Chris Lever - Freelance SEO Consultant Availible for Hire. Specialist in Technical SEO Audits, Strategy and Implementation.

    Need Help?

    • BB Code
    • Cookie Policy
    • Terms of Use
    • Privacy Policy
    • HTML Sitemap

    Learn More

    • About
    • Availability
    • Popular Posts
    • Projects & Scripts
    • Contact

    Get in Touch

    Chris Lever, Manchester, United Kingdom
    hello@chrisleverseo.com
    +44 0161 883 7660

    © 2023 Chris Lever SEO. All rights reserved. Powered by Xenforo | PF

    • This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
      By continuing to use this site, you are consenting to our use of cookies.
      Accept Learn more…