### Install ButterCMS PHP Wrapper with Composer Source: https://github.com/buttercms/buttercms-php/blob/master/README.md Installs the ButterCMS PHP API wrapper using Composer, the dependency manager for PHP. This is the recommended installation method and allows for easy updates and management of the library. ```bash composer require buttercms/buttercms-php ``` -------------------------------- ### Manual Installation of ButterCMS PHP Wrapper Source: https://github.com/buttercms/buttercms-php/blob/master/README.md Manually includes the ButterCMS PHP API wrapper by requiring the main ButterCMS.php file. This method is an alternative if Composer is not used, requiring direct download of the release. ```php require_once('/path/to/buttercms-php/src/ButterCMS.php'); ``` -------------------------------- ### Search Blog Posts with ButterCMS PHP SDK Source: https://context7.com/buttercms/buttercms-php/llms.txt This example demonstrates how to search for blog posts using a query string and optional parameters for pagination with the ButterCMS PHP SDK. It retrieves the total count of matching posts and iterates through the results, displaying the title, URL, and summary for each post. Error handling for search API calls is included. ```php 1, 'page_size' => 20 ]; $result = $butterCms->searchPosts($searchQuery, $params); $meta = $result->getMeta(); echo "Found {$meta['count']} posts matching '{$$searchQuery}'\n\n"; $posts = $result->getPosts(); foreach ($posts as $post) { echo "Title: " . $post->getTitle() . "\n"; echo "URL: " . $post->getUrl() . "\n"; echo "Summary: " . $post->getSummary() . "\n\n"; } } catch (GuzzleHttp\Exception\BadResponseException $e) { echo "Search error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Fetch Categories and Tags from ButterCMS Source: https://context7.com/buttercms/buttercms-php/llms.txt This PHP example demonstrates how to retrieve blog taxonomy information including categories and tags with post counts from ButterCMS. It requires an API token and handles HTTP exceptions. The code shows how to fetch all categories with recent posts, individual categories, all tags, and specific tags by slug. ```php 'recent_posts']; $categories = $butterCms->fetchCategories($params); echo "Categories:\n"; foreach ($categories as $category) { echo "- " . $category->getName() . " (slug: " . $category->getSlug() . ")\n"; } echo "\n"; // Fetch single category $category = $butterCms->fetchCategory('technology'); echo "Category: " . $category->getName() . "\n\n"; // Fetch all tags $tags = $butterCms->fetchTags(); echo "Tags:\n"; foreach ($tags as $tag) { echo "- " . $tag->getName() . " (slug: " . $tag->getSlug() . ")\n"; } echo "\n"; // Fetch single tag $tag = $butterCms->fetchTag('php'); echo "Tag: " . $tag->getName() . "\n"; } catch (GuzzleHttp\Exception\BadResponseException $e) { echo "Error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Create and Update Pages (PHP) Source: https://context7.com/buttercms/buttercms-php/llms.txt This code snippet illustrates how to create new pages and update existing pages within the ButterCMS platform. It demonstrates the use of API tokens for write access and provides examples of setting page types, slugs, statuses, titles, and custom fields. Error handling for missing write tokens is also included. ```php 'landing-page', 'slug' => 'new-landing-page', 'status' => 'published', 'title' => 'New Landing Page', 'fields' => [ 'hero_title' => 'Welcome to Our Site', 'hero_subtitle' => 'We provide amazing services', 'hero_image' => 'https://example.com/hero.jpg', 'cta_text' => 'Get Started', 'cta_link' => '/signup', 'sections' => [ [ 'heading' => 'Section 1', 'content' => 'This is the first section' ], [ 'heading' => 'Section 2', 'content' => 'This is the second section' ] ] ] ]; $createResponse = $butterCms->createPage($pageData); echo "Page created successfully\n"; // Update an existing page $updatedData = [ 'title' => 'Updated Landing Page Title', 'fields' => [ 'hero_title' => 'Updated Hero Title', 'cta_text' => 'Sign Up Now' ] ]; $updateResponse = $butterCms->updatePage('new-landing-page', $updatedData); echo "Page updated successfully\n"; } catch (\BadMethodCallException $e) { echo "Write token not configured\n"; } catch (GuzzleHttp\Exception\BadResponseException $e) { echo "Error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Fetch Authors with Recent Posts from ButterCMS Source: https://context7.com/buttercms/buttercms-php/llms.txt This PHP example shows how to retrieve blog authors from ButterCMS with optional inclusion of their recent posts. It requires an API token and handles HTTP exceptions. The code demonstrates fetching all authors with their profile information and recent posts, as well as retrieving individual authors by slug. ```php 'recent_posts' ]; $authors = $butterCms->fetchAuthors($params); foreach ($authors as $author) { echo "Name: " . $author->getFirstName() . " " . $author->getLastName() . "\n"; echo "Slug: " . $author->getSlug() . "\n"; echo "Email: " . $author->getEmail() . "\n"; echo "Title: " . $author->getTitle() . "\n"; echo "Bio: " . $author->getBio() . "\n"; echo "Profile Image: " . $author->getProfileImage() . "\n"; echo "Twitter: " . $author->getTwitterHandle() . "\n"; echo "LinkedIn: " . $author->getLinkedinUrl() . "\n"; echo "Facebook: " . $author->getFacebookUrl() . "\n"; echo "Instagram: " . $author->getInstagramUrl() . "\n"; echo "Pinterest: " . $author->getPinterestUrl() . "\n\n"; } // Fetch single author $author = $butterCms->fetchAuthor('john-doe'); echo "Author found: " . $author->getFirstName() . " " . $author->getLastName() . "\n"; } catch (GuzzleHttp\Exception\BadResponseException $e) { echo "Error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Manage Pages with ButterCMS PHP API Source: https://github.com/buttercms/buttercms-php/blob/master/README.md Demonstrates the creation, fetching, updating, and retrieval of pages using the ButterCMS PHP API. Includes examples of accessing page fields and handling API responses, along with error handling for non-200 responses and JSON parsing issues. ```php use ButterCMS\ButterCMS; $butterCms = new ButterCMS('', ''); // Create a Page $writeApiStatus = $butterCms->createPage($params); // Fetch a Page $page = $butterCms->fetchPage('about', 'welcome-to-the-site'); // Update a Page $pageData = json_decode(json_encode($page), true); $pageData['title'] = 'New Page Title'; $writeApiStatus = $butterCms->updatePage('welcome-to-the-site', $pageData); // These are equivalent echo $page->getFields()['some-field']; echo $page->getField('some-field'); $pagesResponse = $butterCms->fetchPages('news', ['breaking-news' => true]); var_dump($pagesResponse->getMeta()['count']); foreach ($pagesResponse->getPages() as $page) { echo $page->getSlug(); } // Error Handling try { $butterCms->fetchPage('about', 'non-existent-page'); } catch (GuzzleHttp\Exception\BadResponseException $e) { // Happens for any non-200 response from the API var_dump($e->getMessage()); } catch (\UnexpectedValueException $e) { // Happens if there is an issue parsing the JSON response var_dump($e->getMessage()); } ``` -------------------------------- ### Manage Collections with ButterCMS PHP API Source: https://github.com/buttercms/buttercms-php/blob/master/README.md Provides examples for creating, fetching, updating, and deleting collection items using the ButterCMS PHP API. It also shows how to retrieve lists of collections and individual collection items, including error handling for deprecated methods. ```php use ButterCMS\ButterCMS; $butterCms = new ButterCMS('', ''); $writeApiStatus = $butterCms->createCollectionItem('collection_key', [ 'status' => 'published', 'fields' => [ [ 'field1_key': 'Field value', 'field2_key': 'Field value', ] ] ]); // Get list of specific collections $collectionsResponse = $butterCms->fetchCollections(['collection_key'], ['locale' => 'en']); // Get a collection from the list $collection = $collectionsResponse->getCollection('collection_key'); // Get collection items $items = $collection->getItems(); // Update a specific item $item = $items[0]; $itemData = json_decode(json_encode($item), true); $itemData['fields']['field1_key'] = 'New field value'; $writeApiStatus = $butterCms->updateCollectionItem($collection->getKey(), $item->getId(), $itemData); // Delete a specific item $deleteSuccess = $butterCms->deleteCollectionItem($collection->getKey(), $item->getId()); // Legacy - deprecated $contentFields = $butterCms->fetchContentFields(['collection_key'], ['locale' => 'en']); ``` -------------------------------- ### Fetch Page Content with ButterCMS PHP SDK Source: https://context7.com/buttercms/buttercms-php/llms.txt Illustrates how to retrieve specific page content by its type and slug using the ButterCMS PHP SDK. The example shows how to pass optional parameters like preview mode and locale, access standard page fields, and retrieve custom fields using helper methods. It also includes error handling for page not found and other API errors. ```php 1, // Include draft content 'locale' => 'en' // Specify language ]; $page = $butterCms->fetchPage('landing-page', 'homepage-slug', $params); echo "Page Slug: " . $page->getSlug() . "\n"; echo "Page Type: " . $page->getPageType() . "\n"; echo "Published: " . $page->getPublished() . "\n"; echo "Status: " . $page->getStatus() . "\n"; // Access custom fields (method 1) $fields = $page->getFields(); echo "Hero Title: " . $fields['hero_title'] . "\n"; echo "Hero Image: " . $fields['hero_image'] . "\n"; // Access custom fields (method 2 - preferred) echo "CTA Text: " . $page->getField('cta_text') . "\n"; echo "CTA Link: " . $page->getField('cta_link') . "\n"; // Access with default value if field doesn't exist $subtitle = $page->getField('subtitle', 'Default Subtitle'); echo "Subtitle: " . $subtitle . "\n"; // Check page status if ($page->isPublished()) { echo "This page is live\n"; } elseif ($page->isDraft()) { echo "This page is in draft mode\n"; } } catch (GuzzleHttp\Exception\BadResponseException $e) { if ($e->getResponse()->getStatusCode() === 404) { echo "Page not found\n"; } else { echo "Error: " . $e->getMessage() . "\n"; } } ``` -------------------------------- ### Include ButterCMS PHP Wrapper Autoloader Source: https://github.com/buttercms/buttercms-php/blob/master/README.md Includes the Composer autoloader to make the ButterCMS PHP API wrapper classes available in your project. This should be called after installing via Composer. ```php require_once('vendor/autoload.php'); ``` -------------------------------- ### Fetch Multiple Pages with Filtering (PHP) Source: https://context7.com/buttercms/buttercms-php/llms.txt This snippet demonstrates how to retrieve multiple pages of a specific type using filtering parameters. It utilizes the ButterCMS PHP library to fetch pages based on criteria like 'featured', 'category', and locale. The example also shows how to access pagination metadata and iterate through the retrieved pages. ```php true, 'category' => 'products', 'page' => 1, 'page_size' => 10, 'locale' => 'en' ]; $pagesResponse = $butterCms->fetchPages('product-page', $params); // Access pagination metadata $meta = $pagesResponse->getMeta(); echo "Total pages: " . $meta['count'] . "\n"; echo "Previous page: " . ($meta['previous_page'] ?? 'none') . "\n"; echo "Next page: " . ($meta['next_page'] ?? 'none') . "\n\n"; // Iterate through pages $pages = $pagesResponse->getPages(); foreach ($pages as $page) { echo "Slug: " . $page->getSlug() . "\n"; echo "Product Name: " . $page->getField('product_name') . "\n"; echo "Price: $" . $page->getField('price', 0) . "\n"; echo "Description: " . $page->getField('description') . "\n\n"; } } catch (GuzzleHttp\Exception\BadResponseException $e) { echo "Error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Create, Update, and Delete Collection Items in ButterCMS Source: https://context7.com/buttercms/buttercms-php/llms.txt This PHP example demonstrates how to perform CRUD operations on ButterCMS collection items with field validation. It requires both read and write API tokens and handles exceptions for unauthorized operations. The code creates, updates, and deletes collection items while managing item data structures. ```php 'published', 'fields' => [ 'name' => 'Premium Widget', 'price' => 99.99, 'description' => 'High-quality premium widget', 'sku' => 'WIDGET-001', 'in_stock' => true, 'categories' => ['electronics', 'featured'] ] ]; $createResponse = $butterCms->createCollectionItem('products', $itemData); echo "Collection item created\n"; // Fetch collection to get item ID $collectionsResponse = $butterCms->fetchCollections(['products']); $products = $collectionsResponse->getCollection('products'); $items = $products->getItems(); $firstItem = $items[0]; // Update collection item $itemId = $firstItem->getId(); $updateData = json_decode(json_encode($firstItem), true); $updateData['fields']['price'] = 89.99; $updateData['fields']['in_stock'] = false; $updateResponse = $butterCms->updateCollectionItem('products', $itemId, $updateData); echo "Collection item updated\n"; // Delete collection item $deleteSuccess = $butterCms->deleteCollectionItem('products', $itemId); if ($deleteSuccess) { echo "Collection item deleted\n"; } } catch (\BadMethodCallException $e) { echo "Write token required for this operation\n"; } catch (GuzzleHttp\Exception\BadResponseException $e) { echo "Error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Create Blog Post with ButterCMS PHP SDK Source: https://context7.com/buttercms/buttercms-php/llms.txt Demonstrates how to create a new blog post using the ButterCMS PHP SDK. It includes setting the title, slug, body content, metadata, publishing status, featured image, categories, tags, and author. Error handling for missing write tokens and API errors is included. ```php 'My New Blog Post', 'slug' => 'my-new-blog-post', 'body' => '

This is the post content with HTML formatting.

', 'summary' => 'A brief summary of the post', 'seo_title' => 'My New Blog Post - SEO Optimized Title', 'meta_description' => 'This is the meta description for search engines', 'status' => 'published', // or 'draft', 'scheduled' 'featured_image' => 'https://example.com/image.jpg', 'featured_image_alt' => 'Description of the image', 'categories' => ['category-slug-1', 'category-slug-2'], 'tags' => ['tag-slug-1', 'tag-slug-2'], 'author' => 'author-slug' ]; $writeResponse = $butterCms->createPost($postData); // Check if write operation succeeded if ($writeResponse) { echo "Post created successfully\n"; } } catch (\BadMethodCallException $e) { echo "Write token not configured: " . $e->getMessage() . "\n"; } catch (GuzzleHttp\Exception\BadResponseException $e) { echo "API Error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Blog Engine - Create Post Source: https://github.com/buttercms/buttercms-php/blob/master/README.md Creates a new blog post. ```APIDOC ## POST /posts ### Description Creates a new blog post with the provided data. ### Method POST ### Endpoint /posts #### Request Body - **title** (string) - Required - The title of the post. - **body** (string) - Required - The content of the post. - **slug** (string) - Required - The unique slug for the post. - **status** (string) - Optional - The status of the post (e.g., 'draft', 'published'). Defaults to 'draft'. ### Request Example ```php use ButterCMS\ButterCMS; $butterCms = new ButterCMS('', ''); $params = [ 'title' => 'My New Post', 'body' => 'This is the content of my new post.', 'slug' => 'my-new-post' ]; $writeApiStatus = $butterCms->createPost($params); ``` ### Response #### Success Response (201) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "created" } ``` ``` -------------------------------- ### Create, Fetch, Update, and Delete Blog Posts using ButterCMS PHP SDK Source: https://github.com/buttercms/buttercms-php/blob/master/README.md Illustrates the full lifecycle management of blog posts using the ButterCMS PHP SDK. This includes creating a new post, fetching a single post by its slug, updating an existing post, and querying for posts. Requires the ButterCMS PHP SDK and authentication tokens. ```php use ButterCMS\ButterCMS; $butterCms = new ButterCMS('', ''); // Create a Post $writeApiStatus = $butterCms->createPost($params); // Query for one post $response = $butterCms->fetchPost('post-slug'); $post = $response->getPost(); echo $post->getTitle(); // Update a Post $postData = json_decode(json_encode($post), true); $postData['title'] = 'New Post Title'; $writeApiStatus = $butterCms->updatePost('post-slug', $postData); ``` -------------------------------- ### Fetch and Display Blog Posts using ButterCMS PHP SDK Source: https://github.com/buttercms/buttercms-php/blob/master/README.md Demonstrates how to fetch a list of blog posts, retrieve metadata (like pagination), and access individual post attributes such as title, slug, and author details. It also shows how to loop through multiple posts. Requires the ButterCMS PHP SDK and an authentication token. ```php use ButterCMS\ButterCMS; $butterCms = new ButterCMS('', ''); // Posts $result = $butterCms->fetchPosts(['page' => 1]); $meta = $result->getMeta(); // Meta information like pagination print_r($meta); $posts = $result->getPosts(); // Get posts array off of result $post = $posts[0]; // Get the first post echo $post->getTitle(); // Access attributes using getXxxx() format. echo $post->getSlug(); $author = $post->getAuthor(); // Access nested objects: Author, Tags, Categories like so echo $author->getFirstName(); echo $author->getLastName(); // Loop through posts foreach ($posts as $post) { echo $post->getTitle(); } ``` -------------------------------- ### Fetch RSS Feed and Search Posts using ButterCMS PHP SDK Source: https://github.com/buttercms/buttercms-php/blob/master/README.md Demonstrates how to fetch an RSS feed for the blog as a SimpleXMLElement object and how to perform searches across blog posts. Requires the ButterCMS PHP SDK and an authentication token. ```php use ButterCMS\ButterCMS; $butterCms = new ButterCMS('', ''); // Feeds - returns a SimpleXMLElement object $feed = $butterCms->fetchFeed('rss'); // Search $butterCms->searchPosts('query', ['page' => 1]); ``` -------------------------------- ### Initialize ButterCMS PHP Client Source: https://github.com/buttercms/buttercms-php/blob/master/README.md Initializes the ButterCMS client with authentication tokens. It accepts a READ token for all read operations and optionally a WRITE token for write operations. ```php use ButterCMS\ButterCMS; $butterCms = new ButterCMS( '', '' // Optional ); ``` -------------------------------- ### Blog Engine - Fetch Posts Source: https://github.com/buttercms/buttercms-php/blob/master/README.md Fetches a list of blog posts with support for pagination. ```APIDOC ## GET /posts ### Description Fetches a list of blog posts. Supports pagination and includes meta information. ### Method GET ### Endpoint /posts #### Query Parameters - **page** (integer) - Optional - The page number to retrieve. - **page_size** (integer) - Optional - The number of posts per page. ### Request Example ```php use ButterCMS\ButterCMS; $butterCms = new ButterCMS(''); $result = $butterCms->fetchPosts(['page' => 1, 'page_size' => 10]); $posts = $result->getPosts(); ``` ### Response #### Success Response (200) - **meta** (object) - Contains pagination information. - **posts** (array) - An array of post objects. #### Response Example ```json { "meta": { "count": 10, "next_page": "/v2/posts?page=2&page_size=10", "previous_page": null }, "posts": [ { "title": "Example Post Title", "slug": "example-post-slug", "author": { "first_name": "John", "last_name": "Doe" }, "tags": [], "categories": [], "created": "2023-10-27T10:00:00Z" } ] } ``` ``` -------------------------------- ### Initialize ButterCMS Client in PHP Source: https://context7.com/buttercms/buttercms-php/llms.txt Initializes the ButterCMS client for read-only or content management operations using API tokens. This client is built on Guzzle HTTP and requires PHP 8.0 or higher. It handles authentication and request formatting. ```php '); $butterCms->fetchTags(); ``` ### Response #### Success Response (200) - **tags** (array) - An array of tag objects. #### Response Example ```json { "tags": [ { "slug": "php", "name": "PHP" } ] } ``` ``` -------------------------------- ### Manage Authors, Categories, and Tags using ButterCMS PHP SDK Source: https://github.com/buttercms/buttercms-php/blob/master/README.md Shows how to retrieve lists and individual items for authors, categories, and tags using the ButterCMS PHP SDK. It includes fetching authors and categories with associated recent posts, and fetching tags. Requires the ButterCMS PHP SDK and an authentication token. ```php use ButterCMS\ButterCMS; $butterCms = new ButterCMS('', ''); // Authors $butterCms->fetchAuthor('author-slug'); $butterCms->fetchAuthors(['include' => 'recent_posts']); // Categories $butterCms->fetchCategory('category-slug'); $butterCms->fetchCategories(['include' => 'recent_posts']); // Tags $butterCms->fetchTag('tag-slug'); $butterCms->fetchTags(); ``` -------------------------------- ### Custom HTTP Client Configuration in PHP Source: https://context7.com/buttercms/buttercms-php/llms.txt Illustrates how to inject custom Guzzle HTTP clients for read and write operations to control headers, timeouts, proxies, and other options. After configuration, all SDK requests use the provided clients. Requires Guzzle and appropriate constructor tokens. ```php [ 'X-Butter-Client' => 'PHP/3.0.1', 'Accept-Encoding' => 'gzip', 'X-Custom-Header' => 'CustomValue' ], 'timeout' => 30, 'connect_timeout' => 5, 'http_errors' => true, 'verify' => true, 'proxy' => [ 'http' => 'tcp://proxy.example.com:8080', 'https' => 'tcp://proxy.example.com:8080' ] ]); // Set custom client $butterCms->setReadClient($customReadClient); // Create custom write client $customWriteClient = new Client([ 'headers' => [ 'Authorization' => 'Token your_write_token', 'X-Butter-Client' => 'PHP/3.0.1', 'Accept-Encoding' => 'gzip' ], 'timeout' => 60 ]); $butterCms->setWriteClient($customWriteClient); // Now all requests will use the custom clients $posts = $butterCms->fetchPosts(); // Retrieve configured clients for inspection $readClient = $butterCms->getReadClient(); $writeClient = $butterCms->getWriteClient(); ``` -------------------------------- ### Feeds - Fetch Feed Source: https://github.com/buttercms/buttercms-php/blob/master/README.md Fetches blog content in a specified feed format (e.g., RSS, Atom). ```APIDOC ## GET /feeds/{format} ### Description Fetches blog content formatted as an RSS or Atom feed. ### Method GET ### Endpoint /feeds/{format} #### Path Parameters - **format** (string) - Required - The format of the feed (e.g., 'rss', 'atom'). ### Request Example ```php use ButterCMS\ButterCMS; $butterCms = new ButterCMS(''); $feed = $butterCms->fetchFeed('rss'); // Returns a SimpleXMLElement object ``` ### Response #### Success Response (200) - **feed** (SimpleXMLElement) - An XML object representing the feed content. #### Response Example ```xml ButterCMS Blog Example Post Title https://yourdomain.com/blog/example-post-slug ... ``` ``` -------------------------------- ### Blog Engine - Fetch Single Post Source: https://github.com/buttercms/buttercms-php/blob/master/README.md Fetches a single blog post by its slug. ```APIDOC ## GET /posts/{slug} ### Description Fetches a single blog post using its unique slug. ### Method GET ### Endpoint /posts/{slug} #### Path Parameters - **slug** (string) - Required - The slug of the post to retrieve. ### Request Example ```php use ButterCMS\ButterCMS; $butterCms = new ButterCMS(''); $response = $butterCms->fetchPost('post-slug'); $post = $response->getPost(); ``` ### Response #### Success Response (200) - **post** (object) - The requested post object. #### Response Example ```json { "post": { "title": "Example Post Title", "slug": "example-post-slug", "author": { "first_name": "John", "last_name": "Doe" }, "tags": [], "categories": [], "created": "2023-10-27T10:00:00Z" } } ``` ``` -------------------------------- ### Generate RSS/Atom Feed in PHP Source: https://context7.com/buttercms/buttercms-php/llms.txt Demonstrates how to fetch and output RSS, Atom, or Sitemap XML feeds using the ButterCMS PHP client. It prints feed metadata, iterates items, and sets the correct content-type. Requires a valid API token and proper error handling for network or HTTP issues. ```php fetchFeed('rss'); // $rssFeed is a SimpleXMLElement object echo "Feed Title: " . $rssFeed->channel->title . "\n"; echo "Feed Description: " . $rssFeed->channel->description . "\n"; echo "Feed Link: " . $rssFeed->channel->link . "\n\n"; // Iterate through feed items foreach ($rssFeed->channel->item as $item) { echo "Title: " . $item->title . "\n"; echo "Link: " . $item->link . "\n"; echo "Published: " . $item->pubDate . "\n"; echo "Description: " . $item->description . "\n\n"; } // Output feed as XML string header('Content-Type: application/rss+xml; charset=utf-8'); echo $rssFeed->asXML(); // Alternative: Fetch Atom feed // $atomFeed = $butterCms->fetchFeed('atom'); // Alternative: Fetch Sitemap // $sitemap = $butterCms->fetchFeed('sitemap'); } catch (GuzzleHttp\Exception\BadResponseException $e) { echo "Error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Fetch Single Blog Post by Slug in PHP Source: https://context7.com/buttercms/buttercms-php/llms.txt Retrieves a specific blog post using its slug, providing full content and metadata. It demonstrates accessing various post properties like title, URL, body, SEO details, and featured image. Includes error handling for not found posts and general API errors. ```php fetchPost('example-post-slug'); $post = $response->getPost(); // Access all post properties echo "Title: " . $post->getTitle() . "\n"; echo "URL: " . $post->getUrl() . "\n"; echo "Body: " . $post->getBody() . "\n"; echo "SEO Title: " . $post->getSeoTitle() . "\n"; echo "Meta Description: " . $post->getMetaDescription() . "\n"; echo "Featured Image Alt: " . $post->getFeaturedImageAlt() . "\n"; } catch (GuzzleHttp\Exception\BadResponseException $e) { if ($e->getResponse()->getStatusCode() === 404) { echo "Post not found\n"; } else { echo "Error: " . $e->getMessage() . "\n"; } } ``` -------------------------------- ### Search - Search Posts Source: https://github.com/buttercms/buttercms-php/blob/master/README.md Searches blog posts based on a query string. ```APIDOC ## GET /search ### Description Searches through blog posts for a given query string. Supports pagination. ### Method GET ### Endpoint /search #### Query Parameters - **query** (string) - Required - The search term. - **page** (integer) - Optional - The page number for search results. ### Request Example ```php use ButterCMS\ButterCMS; $butterCms = new ButterCMS(''); $butterCms->searchPosts('search query', ['page' => 1]); ``` ### Response #### Success Response (200) - **results** (array) - An array of post objects matching the search query. - **meta** (object) - Contains pagination information for the search results. #### Response Example ```json { "results": [ { "title": "Example Post Title", "slug": "example-post-slug" } ], "meta": { "count": 1, "next_page": null, "previous_page": null } } ``` ``` -------------------------------- ### Categories - Fetch All Categories Source: https://github.com/buttercms/buttercms-php/blob/master/README.md Fetches a list of all categories, with an option to include their recent posts. ```APIDOC ## GET /categories ### Description Fetches a list of all categories. You can optionally include recent posts for each category. ### Method GET ### Endpoint /categories #### Query Parameters - **include** (string) - Optional - Comma-separated list of related resources to include (e.g., 'recent_posts'). ### Request Example ```php use ButterCMS\ButterCMS; $butterCms = new ButterCMS(''); $butterCms->fetchCategories(['include' => 'recent_posts']); ``` ### Response #### Success Response (200) - **categories** (array) - An array of category objects. #### Response Example ```json { "categories": [ { "slug": "technology", "name": "Technology", "recent_posts": [] } ] } ``` ``` -------------------------------- ### Configure API Base URL with Environment Variable (PHP) Source: https://context7.com/buttercms/buttercms-php/llms.txt This PHP snippet demonstrates how to set the API_BASE_URL environment variable to point to a custom API endpoint, useful for testing or custom deployments. It shows how to initialize the ButterCMS client with this custom URL and then how to unset the variable for default production usage. ```php fetchPosts(); // For production, unset or use default putenv('API_BASE_URL'); // Clear environment variable // Production usage $productionClient = new ButterCMS('production_api_token'); $pages = $productionClient->fetchPages('landing-page'); ``` -------------------------------- ### Fetch Collections (Content Fields) (PHP) Source: https://context7.com/buttercms/buttercms-php/llms.txt This snippet demonstrates retrieving collection items using the ButterCMS PHP library. It shows how to fetch multiple collections based on keys, specify a locale, and control the depth of nested collections. The code illustrates accessing fields within collection items and handles cases where fields might be missing. ```php 'en', 'levels' => 2 // Depth of nested collections to fetch ]; $collectionsResponse = $butterCms->fetchCollections($collectionKeys, $options); // Get all collections $collections = $collectionsResponse->getCollections(); // Access specific collection $products = $collectionsResponse->getCollection('products'); if ($products) { echo "Collection Key: " . $products->getKey() . "\n\n"; // Iterate through collection items $items = $products->getItems(); foreach ($items as $item) { echo "Item ID: " . $item->getId() . "\n"; // Access fields $fields = $item->getFields(); echo "Name: " . ($fields['name'] ?? 'N/A') . "\n"; echo "Price: " . ($fields['price'] ?? 'N/A') . "\n"; echo "Description: " . ($fields['description'] ?? 'N/A') . "\n"; echo "Image: " . ($fields['image'] ?? 'N/A') . "\n\n"; } } // Access testimonials collection $testimonials = $collectionsResponse->getCollection('testimonials'); if ($testimonials) { foreach ($testimonials->getItems() as $testimonial) { $fields = $testimonial->getFields(); echo "Customer: " . $fields['customer_name'] . "\n"; echo "Quote: " . $fields['quote'] . "\n"; echo "Rating: " . $fields['rating'] . "/5\n\n"; } } } catch (GuzzleHttp\Exception\BadResponseException $e) { echo "Error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Update Blog Post with ButterCMS PHP SDK Source: https://context7.com/buttercms/buttercms-php/llms.txt Shows how to update an existing blog post identified by its slug using the ButterCMS PHP SDK. The process involves fetching the post, modifying its data (like title, body, and status), and then sending the updated information back to the API. It includes error handling for API request failures. ```php fetchPost('my-post-slug'); $post = $response->getPost(); // Convert to array for modification $postData = json_decode(json_encode($post), true); // Update specific fields $postData['title'] = 'Updated Post Title'; $postData['body'] = '

Updated content goes here

'; $postData['status'] = 'published'; // Send update $writeResponse = $butterCms->updatePost('my-post-slug', $postData); echo "Post updated successfully\n"; } catch (GuzzleHttp\Exception\BadResponseException $e) { echo "Error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Blog Engine - Update Post Source: https://github.com/buttercms/buttercms-php/blob/master/README.md Updates an existing blog post identified by its slug. ```APIDOC ## PUT /posts/{slug} ### Description Updates an existing blog post identified by its slug with new data. ### Method PUT ### Endpoint /posts/{slug} #### Path Parameters - **slug** (string) - Required - The slug of the post to update. #### Request Body - **title** (string) - Optional - The new title of the post. - **body** (string) - Optional - The new content of the post. ### Request Example ```php use ButterCMS\ButterCMS; $butterCms = new ButterCMS('', ''); $postData = [ 'title' => 'Updated Post Title', 'body' => 'This is the updated content.' ]; $writeApiStatus = $butterCms->updatePost('post-slug', $postData); ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "updated" } ``` ``` -------------------------------- ### Authors - Fetch All Authors Source: https://github.com/buttercms/buttercms-php/blob/master/README.md Fetches a list of all authors, with an option to include their recent posts. ```APIDOC ## GET /authors ### Description Fetches a list of all authors. You can optionally include recent posts for each author. ### Method GET ### Endpoint /authors #### Query Parameters - **include** (string) - Optional - Comma-separated list of related resources to include (e.g., 'recent_posts'). ### Request Example ```php use ButterCMS\ButterCMS; $butterCms = new ButterCMS(''); $butterCms->fetchAuthors(['include' => 'recent_posts']); ``` ### Response #### Success Response (200) - **authors** (array) - An array of author objects. #### Response Example ```json { "authors": [ { "slug": "john-doe", "first_name": "John", "last_name": "Doe", "recent_posts": [] } ] } ``` ``` -------------------------------- ### Tags - Fetch Single Tag Source: https://github.com/buttercms/buttercms-php/blob/master/README.md Fetches a single tag by its slug. ```APIDOC ## GET /tags/{slug} ### Description Fetches a single tag's details using its unique slug. ### Method GET ### Endpoint /tags/{slug} #### Path Parameters - **slug** (string) - Required - The slug of the tag to retrieve. ### Request Example ```php use ButterCMS\ButterCMS; $butterCms = new ButterCMS(''); $butterCms->fetchTag('tag-slug'); ``` ### Response #### Success Response (200) - **tag** (object) - The requested tag object. #### Response Example ```json { "tag": { "slug": "php", "name": "PHP" } } ``` ```