• Plans & Pricing
  • Log in
  • Get started
  • WordPress Hosting
  • WordPress for Agencies
  • Become an Affiliate
  • Domain Names
  • AI Website Builder
  • Website Builder
  • Create a Blog
  • Newsletter
  • Professional Email
  • Website Design Services
  • Commerce
  • WordPress Studio
  • Enterprise WordPress 
  • Overview
  • WordPress Themes
  • WordPress Plugins
  • WordPress Patterns
  • Google Apps
  • Support Center
  • WordPress News
  • Business Name Generator
  • Logo Maker
  • Discover New Posts
  • Popular Tags
  • Blog Search
Get started
  • Sign up
  • Log in
About
  • Plans & Pricing
Products
  • WordPress Hosting
  • WordPress for Agencies
  • Become an Affiliate
  • Domain Names
  • AI Website Builder
  • Website Builder
  • Create a Blog
  • Newsletter
  • Professional Email
  • Website Design Services
  • Commerce
  • WordPress Studio
  • Enterprise WordPress  
Features
  • Overview
  • WordPress Themes
  • WordPress Plugins
  • WordPress Patterns
  • Google Apps
Resources
  • Support Center
  • WordPress News
  • Business Name Generator
  • Logo Maker
  • Discover New Posts
  • Popular Tags
  • Blog Search
Jetpack App
  • Learn more
  • Support Center
  • Guides
  • Courses
  • Forums
  • Contact
Search
  • Support Center
  • Guides
  • Courses
  • Forums
  • Contact
Forums / Trouble Accessing WordPress User Data via API – Need Help Retrieving Names

Trouble Accessing WordPress User Data via API – Need Help Retrieving Names

  • Unknown's avatar
    whitedragon32 · Member · Mar 12, 2025 at 4:18 am
    • Copy link Copy link
    • Add topic to favorites Add topic to favorites

    I am running into issues with enabling API access or accessing specific WordPress functions on my site hosted with Bluehost through API. I have successfully set up a custom API endpoint to access WPForms data, and I have also used my AffiliateWP plugin’s additional API add-on to retrieve affiliate data. However, I am currently trying to retrieve the names of the users (NOT their usernames) from my WordPress site it’s self, but keep running into issues.

    My AffiliateWP plugin links affiliates to WordPress users using user IDs. To fetch details about an affiliate, I need to look up the user based on the user ID and retrieve their name (not username). Unfortunately, whenever I attempt to make an API call to fetch user information, I encounter errors.

    Could you please guide me on how to enable access to these WordPress-specific API functions? Are there any settings or configurations I may have missed?

    Below is the current code I am trying to run that I am getting errors from:

    function fetchAffiliateWPAffiliates() {
      var sheet = SpreadsheetApp.openById("My_Spreadsheet_ID_Here").getActiveSheet(); // Spreadsheet ID
    
      // Custom API URL for fetching affiliates
      var affwpApiUrl = "https://fireantlogistics.com/wp-json/custom-api/v1/affiliates";  // Use your new custom API endpoint here
      var affwpHeaders = {
        "Authorization": "Basic AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", // Your API key, encode accordingly
        "Content-Type": "application/json"
      };
      var affwpOptions = { "method": "get", "headers": affwpHeaders, "muteHttpExceptions": true };
    
      try {
        var response = UrlFetchApp.fetch(affwpApiUrl, affwpOptions);
        var responseData = response.getContentText();  // Get the raw response text
        Logger.log("API Response: " + responseData); // Log the raw API response for debugging
    
        var affiliates;
        
        // Try to parse the JSON response
        try {
          affiliates = JSON.parse(responseData); // Parse the JSON response
        } catch (e) {
          Logger.log("Error parsing API response: " + e.toString());
          return;  // Stop execution if JSON parsing fails
        }
    
        if (!Array.isArray(affiliates)) {
          Logger.log("API response is not an array: " + JSON.stringify(affiliates));
          return;  // Exit if the response is not an array
        }
    
        if (affiliates.length === 0) {
          Logger.log("No affiliates found.");
          return;
        }
    
        var lastRow = sheet.getLastRow();
    
        affiliates.forEach(function (affiliate) {
          var userId = affiliate.user_id;
          var name = fetchUserName(userId); // Fetch full name (First + Last) from WordPress Users API
    
          Logger.log("Affiliate ID: " + affiliate.affiliate_id + ", Name: " + name); // Log the name for debugging
    
          lastRow++;
          sheet.getRange(lastRow, 1, 1, 2).setValues([[affiliate.affiliate_id, name]]);
        });
    
        Logger.log("Affiliate data successfully added.");
      } catch (err) {
        Logger.log("Error during API call: " + err.message);
      }
    }
    
    // Function to fetch user's full name (First + Last) using WordPress Users API
    function fetchUserName(userId) {
      var userApiUrl = "https://fireantlogistics.com/wp-json/wp/v2/users/" + userId;
      var wpOptions = {
        "method": "GET",
        "headers": {
          "Authorization": "Basic " + Utilities.base64Encode("AAAAAAAAAAAAAAAAAAAAAAAAAAAAA") // Encode WordPress API Key
        },
        muteHttpExceptions: true
      };
    
      try {
        var response = UrlFetchApp.fetch(userApiUrl, wpOptions);
        
        // Log the raw response for debugging purposes
        Logger.log("Response from WordPress API for userId " + userId + ": " + response.getContentText());
    
        var userData = JSON.parse(response.getContentText());
    
        // Check if user data exists before accessing the fields
        if (userData && userData.first_name && userData.last_name) {
          var fullName = userData.first_name + " " + userData.last_name; // Combine first and last name
          return fullName;
        } else if (userData && userData.first_name) {
          return userData.first_name; // Only first name
        } else if (userData && userData.last_name) {
          return userData.last_name; // Only last name
        } else {
          return "Unknown"; // Default if no name found
        }
      } catch (err) {
        Logger.log("Error fetching user data: " + err.message);
        return "Error fetching name"; // Return error message if the request fails
      }
    }

    The Errors I keep running into are:

    12:05:02 AM Notice Execution started
    12:05:03 AM Info
    API Response: {"code":"rest_no_route","message":"No route was found matching the URL and request method.","data":{"status":404}}
    
    12:05:03 AM Info
    API response is not an array: {"code":"rest_no_route","message":"No route was found matching the URL and request method.","data":{"status":404}}
    
    12:05:03 AM Notice Execution completed

    Any help you can provide would be greatly appreciated!
    Thank you in advance!

  • Unknown's avatar
    whitedragon32 · Member · Mar 12, 2025 at 5:36 am
    • Copy link Copy link

    It doesn’t give me the option to edit or to delete my Post. So, I’ll just have to make a reply Post with the different info here:
    I tried a new approach and this is the new code, but I am also getting errors on it as well:

    
    function fetchAffiliateWPAffiliates() {
      var sheet = SpreadsheetApp.openById("My_Spreadsheet_ID_Here").getActiveSheet(); // Spreadsheet ID
    
      // Custom API URL for fetching affiliates (AffiliateWP plugin)
      var affwpApiUrl = "https://fireantlogistics.com/wp-json/affwp/v1/affiliates";  // Use your AffiliateWP API endpoint
      var affwpHeaders = {
        "Authorization": "Basic FakeFakeFake", // Your API key, encode accordingly
        "Content-Type": "application/json"
      };
      var affwpOptions = { "method": "get", "headers": affwpHeaders, "muteHttpExceptions": true };
    
      try {
        var response = UrlFetchApp.fetch(affwpApiUrl, affwpOptions);
        var responseData = response.getContentText();  // Get the raw response text
        Logger.log("API Response: " + responseData); // Log the raw API response for debugging
    
        var affiliates;
    
        // Try to parse the JSON response
        try {
          affiliates = JSON.parse(responseData); // Parse the JSON response
        } catch (e) {
          Logger.log("Error parsing API response: " + e.toString());
          return;  // Stop execution if JSON parsing fails
        }
    
        if (!Array.isArray(affiliates)) {
          Logger.log("API response is not an array: " + JSON.stringify(affiliates));
          return;  // Exit if the response is not an array
        }
    
        if (affiliates.length === 0) {
          Logger.log("No affiliates found.");
          return;
        }
    
        var lastRow = sheet.getLastRow();
    
        affiliates.forEach(function (affiliate) {
          var userId = affiliate.user_id;
          var name = fetchUserName(userId); // Fetch full name (First + Last) from WordPress Users API
    
          Logger.log("Affiliate ID: " + affiliate.affiliate_id + ", Name: " + name); // Log the name for debugging
    
          lastRow++;
          sheet.getRange(lastRow, 1, 1, 2).setValues([[affiliate.affiliate_id, name]]);
        });
    
        Logger.log("Affiliate data successfully added.");
      } catch (err) {
        Logger.log("Error during API call: " + err.message);
      }
    }
    
    // Function to fetch user's full name (First + Last) using WordPress Users API
    function fetchUserName(userId) {
      var userApiUrl = "https://fireantlogistics.com/wp-json/wp/v2/users/" + userId;
      var wpOptions = {
        "method": "GET",
        "headers": {
          "Authorization": "Basic " + Utilities.base64Encode("FakeFakeFake") // Encode WordPress API Key
        },
        muteHttpExceptions: true
      };
    
      try {
        var response = UrlFetchApp.fetch(userApiUrl, wpOptions);
    
        // Log the raw response for debugging purposes
        Logger.log("Response from WordPress API for userId " + userId + ": " + response.getContentText());
    
        var userData = JSON.parse(response.getContentText());
    
        // Check if user data exists before accessing the fields
        if (userData && userData.first_name && userData.last_name) {
          var fullName = userData.first_name + " " + userData.last_name; // Combine first and last name
          return fullName;
        } else if (userData && userData.first_name) {
          return userData.first_name; // Only first name
        } else if (userData && userData.last_name) {
          return userData.last_name; // Only last name
        } else {
          return "Unknown"; // Default if no name found
        }
      } catch (err) {
        Logger.log("Error fetching user data: " + err.message);
        return "Error fetching name"; // Return error message if the request fails
      }
    }

    These are the errors here:

    12:46:31 AMInfo 
    Response from WordPress API for userId 8: {"code":"rest_user_cannot_view","message":"Sorry, you are not allowed to list users.","data":{"status":401}}
    
    12:46:31 AM
    InfoAffiliate ID: 7, Name: Unknown12:46:31 AMInfoResponse from WordPress API for userId 9: {"code":"rest_user_cannot_view","message":"Sorry, you are not allowed to list users.","data":{"status":401}}12:46:31 AMInfoAffiliate ID: 8, Name: Unknown
  • Unknown's avatar
    faisalahammad · Member · Mar 12, 2025 at 10:29 am
    • Copy link Copy link

    Hi there,

    Good morning. I hope you’re doing great.

    It looks like you’re using self-hosted WordPress, not WordPress.com. Therefore, it’s recommended to open a support ticket at the following URL for WordPress.org support.

    https://wordpress.org/support/forums/

    To understand the difference between WordPress.com and WordPress.org, please check the article below.

    WP
    WordPress.com vs. WordPress.org
    in WordPress.com Support
    6 min read
    WordPress powers millions of websites, from bloggers and small businesses to massive news sites and companies. This guide will help you to understand the difference between WordPress.com and WordPress.org, and which might be the best fit for your website. Overview of Differences The same WordPress software powers both WordPress.com and WordPress.org sites. One of the main differences is ho

    Have a good day!

    Thanks
    Faisal

  • The topic ‘Trouble Accessing WordPress User Data via API – Need Help Retrieving Names’ is closed to new replies.

Tags

  • account
  • design

About this topic

  • In: Support
  • 2 participants
  • 2 replies
  • Last activity 10 months
  • Latest reply from whitedragon32

Couldn't find what you needed?

Contact us

Contact us

Get answers from our AI assistant, with access to 24/7 expert human support on paid plans.

Browse our guides

Browse our guides

Find step-by-step solutions to common questions in our comprehensive guides.

WordPress.com

Products
  • WordPress Hosting
  • WordPress for Agencies
  • Become an Affiliate
  • Domain Names
  • AI Website Builder
  • Website Builder
  • Create a Blog
  • Professional Email
  • Website Design Services
  • WordPress Studio
  • Enterprise WordPress
Features
  • Overview
  • WordPress Themes
  • WordPress Plugins
  • WordPress Patterns
  • Google Apps
Resources
  • WordPress.com Blog
  • Business Name Generator
  • Logo Maker
  • WordPress.com Reader
  • Accessibility
  • Remove Subscriptions
Help
  • Support Center
  • Guides
  • Courses
  • Forums
  • Contact
  • Developer Resources
Company
  • About
  • Press
  • Terms of Service
  • Privacy Policy
  • Do Not Sell or Share My Personal Information
  • Privacy Notice for California Users
DeutschEspañolFrançaisBahasa IndonesiaItalianoNederlandsPortuguês do BrasilSvenskaTürkçeРусскийالعربيةעִבְרִית日本語한국어简体中文繁體中文English

Mobile Apps

  • Download on the App Store
  • Get it on Google Play

Social Media

  • WordPress.com on Facebook
  • WordPress.com on X (Twitter)
  • WordPress.com on Instagram
  • WordPress.com on YouTube

Automattic

Automattic
Work With Us
    • WordPress.com Forums
    • Sign up
    • Log in
    • Copy shortlink
    • Report this content
    • Manage subscriptions