Content

Category Service

Category Service

Overview

The Category class is part of the Toolstation\Content\Services\Wordpress\Rest namespace and is designed to interact with the WordPress REST API for category-related operations. It provides methods to retrieve categories by their slug, parent category, and placeholder methods for future functionality.

Class Definition

Namespace

namespace Toolstation\Content\Services\Wordpress\Rest;

Constants

  • PREFIX: A constant that defines the base path for accessing WordPress category endpoints in the REST API.
      public const PREFIX = 'wp/v2/categories';
    

Properties

  • $client: An instance of the RestClient class, used to make HTTP requests to the WordPress REST API.
      protected $client;
    

Constructor

  public function __construct(RestClient $client)
  • Parameters:
    • RestClient $client: The client used to perform REST API requests.
  • Description: Initializes the Category service with a RestClient instance.

Methods

getBySlug($slug)

public function getBySlug($slug)
  • Description: Retrieves a category based on its slug. It makes an HTTP GET request to the WordPress REST API endpoint using the slug parameter. If no category is found, it aborts with a 404 error. Returns the first matching category from the response.
  • Returns: Array The category data.
  • Parameters:
    • string $slug: The slug of the category to retrieve.

getByPostId($id)

public function getByPostId($id)
  • Description: A placeholder method intended for future implementation to retrieve a category based on the post ID.
  • Parameters:
    • id (int): The ID of the post for which the category needs to be fetched.
  • Return Type: array The category data (placeholder for future implementation).

getByParentCategory($parentCategory)

public function getByParentCategory($parentCategory)
  • Description: Retrieves categories that are children of a specified parent category by making an HTTP GET request to the WordPress REST API endpoint.
  • Parameters:
    • int $parentCategory: The ID of the parent category.
  • Return Type: array
  • Returns: Collection-A collection of categories that have the specified parent category.

Error Handling

  • abort_if: Used in getBySlug to abort the request with a 404 error if no category is found.

Example Usage

$restClient = new RestClient(); // Assuming RestClient is properly instantiated
$categoryService = new Category($restClient);

// Retrieve a category by slug
$category = $categoryService->getBySlug('my-category-slug');

// Retrieve categories by parent category
$categories = $categoryService->getByParentCategory(123);

Copyright © 2026