wordpress

package module
v0.0.0-...-4da8562 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 5, 2023 License: MIT Imports: 18 Imported by: 0

README

go-wordpress

GoDoc

A Go client library for the Wordpress REST API

Installation

go get github.com/eanavitarte/go-wordpress

Usage

Quick example
package main

import (
  "context"
  "fmt"
  "net/http"

  "github.com/eanavitarte/go-wordpress"
)

func main() {

  tp := wordpress.BasicAuthTransport{
    Username: USER,
    Password: PASSWORD,
  }

  // create wp-api client
  client, _ := wordpress.NewClient(API_BASE_URL, tp.Client())

  ctx := context.Background()

  // for eg, to get current user (GET /users/me)
  currentUser, resp, _ := client.Users.Me(ctx, nil)
  if resp != nil && resp.StatusCode != http.StatusOK {
    // handle error
  }

  // Or you can use your own structs (for custom endpoints, for example)
  // Below is the equivalent of `client.Posts.Get(ctx, 100, nil)`
  var obj MyCustomPostStruct
  resp, err := client.Get(ctx, "/posts/100", nil, &obj)
  // ...

  fmt.Printf("Current user %+v", currentUser)
}

For more examples, see package tests.

For list of supported/implemented endpoints, see Endpoints.md

Authentication

The go-wordpress library does not directly handle authentication. Instead, when creating a new client, pass an http.Client that can handle authentication for you.

Note that when using an authenticated Client, all calls made by the client will include the specified authentication transport token. Therefore, authenticated clients should almost never be shared between different users.

Username/Password or Application Password

A basic authentication (username/password) client for use with the WP-API BasicAuth plugin or Application Passwords plugin is included with the library. An example implementation can be found in example/basicauth/main.go.

OAuth 1.0a

If you use the OAuth 1.0a Server for authentication, you can find an example implementation in example/oauth2/main.go using the oauth1 library (which is very similar to the official OAuth 2.0 library). See the oauth1 docs for complete instructions on using that library.

OAuth 2.0 and JWT

If you are using the JWT plug-in for authentication, you can use the oauth2 library's StaticTokenSource. An example implementation can be found in example/oauth2/main.go. See the oauth2 docs for complete instructions on using that library.

Other authentication styles

For any other authentication methods, you should only need to provide a custom http.Client when creating a new WordPress client.

Pagination

All requests for resource collections (posts, pages, media, revisions, etc.) support pagination. Pagination options are described in the wordpress.ListOptions struct and passed to the list methods directly or as an embedded type of a more specific list options struct (for example wordpress.PostListOptions). Pages information is available via the wordpress.Response struct.

package main

import (
  "context"

  "github.com/eanavitarte/go-wordpress"
)

func main() {
  tp := wordpress.BasicAuthTransport{
    Username: USER,
    Password: PASSWORD,
  }

  // create wp-api client
  client, _ := wordpress.NewClient(API_BASE_URL, tp.Client())

  ctx := context.Background()

  opt := &wordpress.PostListOptions{
    ListOptions: wordpress.ListOptions{PerPage: 10},
  }
  // get all pages of results
  var allPosts []*wordpress.Post
  for {
    posts, resp, err := client.Posts.List(ctx, opt)
    if err != nil {
      return err
    }
    allPosts = append(allPosts, posts...)
    if resp.NextPage == 0 {
      break
    }
    opt.Page = resp.NextPage
  }
}

Test

Note: Before running the tests, ensure that you have set up your test environment

Prerequisites
Setting up test environment
  • Install prequisites (see above)
  • Import ./test-data/go-wordpress.wordpress.2015-08-23.xml to your local test Wordpress installation
  • Upload at least one media to your Wordpress installation (Admin > Media > Upload)
  • Edit one (1) most recent Post to create a revision
  • Edit one (1) most recent Page to create a revision

Running tests

# Set test enviroment
export WP_API_URL=http://192.168.99.100:32777/wp-json/
export WP_USER=<user>
export WP_PASSWD=<password>

cd $GOPATH/src/github.com/robbiet480/go-wordpress
go test

Thanks

Parts of this libreary are an adoption of a previously orphaned project maintained by qorpress. Thanks to their grateful work and contributions.

Parts of this library were inspired (if not outright copied) from Google's excellent go-github library.

Documentation

Overview

Package wordpress provides a Go client library for the WordPress REST API.

Index

Constants

View Source
const (
	PostStatusDraft   = "draft"
	PostStatusPending = "pending"
	PostStatusPrivate = "private"
	PostStatusPublish = "publish"
	PostStatusTrash   = "trash"

	PostTypePost = "post"
	PostTypePage = "page"

	CommentStatusOpen   = "open"
	CommentStatusClosed = "closed"

	CommentStatusApproved   = "approved"
	CommentStatusUnapproved = "unapproved"

	PingStatusOpen   = "open"
	PingStatusClosed = "closed"

	PostFormatStandard = "standard"
	PostFormatAside    = "aside"
	PostFormatGallery  = "gallery"
	PostFormatImage    = "image"
	PostFormatLink     = "link"
	PostFormatStatus   = "status"
	PostFormatQuote    = "quote"
	PostFormatVideo    = "video"
	PostFormatChat     = "chat"
)

Constants for different post values.

View Source
const TimeLayout = "2006-01-02T15:04:05"

TimeLayout is the layout string for a timestamp without timezone information like 2017-12-25T09:54:42

View Source
const TimeWithZoneLayout = "2006-01-02T15:04:05-07:00"

TimeWithZoneLayout is the layout string for a timestamp with timezone information like 2017-09-24T13:28:06+00:00.

Variables

View Source
var DefaultHTTPClient = &http.Client{
	Jar:       nil,
	Transport: DefaultHTTPTransport,
}

DefaultHTTPClient is an http.Client with the DefaultHTTPTransport and (Cookie) Jar set nil.

View Source
var DefaultHTTPTransport = &http.Transport{
	DisableKeepAlives: true,
}

DefaultHTTPTransport is an http.RoundTripper that has DisableKeepAlives set true.

View Source
var ErrURLContainsWPV2 = errors.New("url must not contain /wp/v2")

ErrURLContainsWPV2 is returned from NewClient if URL contains /wp/v2.

View Source
var Location = time.UTC

Location is the time.Location used when decoding timestamps from WordPress.

Functions

This section is empty.

Types

type AvatarURLS

type AvatarURLS struct {
	Size24 string `json:"24,omitempty"`
	Size48 string `json:"48,omitempty"`
	Size96 string `json:"96,omitempty"`
}

AvatarURLS returns different sizes of the users avatar.

type BasicAuthTransport

type BasicAuthTransport struct {
	Username string // WordPress username
	Password string // WordPress password

	// Transport is the underlying HTTP transport to use when making requests.
	// It will default to http.DefaultTransport if nil.
	Transport http.RoundTripper
}

BasicAuthTransport is an http.RoundTripper that authenticates all requests using HTTP Basic Authentication with the provided username and password.

func (*BasicAuthTransport) Client

func (t *BasicAuthTransport) Client() *http.Client

Client returns an *http.Client that makes requests that are authenticated using HTTP Basic Authentication.

func (*BasicAuthTransport) RoundTrip

func (t *BasicAuthTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements the RoundTripper interface.

type CategoriesService

type CategoriesService service

CategoriesService provides access to the category related functions in the WordPress REST API.

func (*CategoriesService) Create

func (c *CategoriesService) Create(ctx context.Context, newCategory *Category) (*Category, *Response, error)

Create creates a new category.

func (*CategoriesService) Delete

func (c *CategoriesService) Delete(ctx context.Context, id int, params interface{}) (*Category, *Response, error)

Delete removes the category with the given id.

func (*CategoriesService) Get

func (c *CategoriesService) Get(ctx context.Context, id int, params interface{}) (*Category, *Response, error)

Get returns a single category for the given id.

func (*CategoriesService) List

List returns a list of categories.

func (*CategoriesService) Update

func (c *CategoriesService) Update(ctx context.Context, id int, post *Category) (*Category, *Response, error)

Update updates a single category with the given id.

type Category

type Category struct {
	ID          int    `json:"id"`
	Count       int    `json:"count"`
	Description string `json:"description"`
	Link        string `json:"link"`
	Name        string `json:"name"`
	Slug        string `json:"slug"`
	Taxonomy    string `json:"taxonomy"`
	Parent      int    `json:"parent"`
}

Category represents a WordPress post/page category.

type CategoryListOptions

type CategoryListOptions struct {
	HideEmpty bool     `url:"hide_empty,omitempty"`    // Whether to hide terms not assigned to any posts.
	Parent    int      `url:"parent,omitempty"`        // Limit result set to terms assigned to a specific parent.
	Post      int      `url:"post,omitempty"`          // Limit result set to terms assigned to a specific post.
	Slug      []string `url:"slug,omitempty,brackets"` // Limit result set to terms with one or more specific slugs.

	ListOptions
}

CategoryListOptions are options that can be passed to List().

type Client

type Client struct {
	// User agent used when communicating with the WordPress API.
	UserAgent string

	// WordPress timezone location
	Location *time.Location

	Categories *CategoriesService
	Comments   *CommentsService
	Media      *MediaService
	Pages      *PagesService
	Posts      *PostsService
	Settings   *SettingsService
	Statuses   *StatusesService
	Tags       *TagsService
	Taxonomies *TaxonomiesService
	Terms      *TermsService
	Types      *TypesService
	Users      *UsersService
	// contains filtered or unexported fields
}

Client is a struct containing values and methods used for interacting with the WordPress API.

func NewClient

func NewClient(baseURL string, httpClient *http.Client) (*Client, error)

NewClient returns an initalized Client for the given baseURL and httpClient.

func (*Client) BasicInfo

func (c *Client) BasicInfo(ctx context.Context) (*RootInfo, *Response, error)

BasicInfo gets basic and publicly available information about the WordPress REST API.

func (*Client) Create

func (c *Client) Create(ctx context.Context, url string, content interface{}, result interface{}) (*Response, error)

Create creates a new item on the WordPress REST API.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, url string, params interface{}, result interface{}) (*Response, error)

Delete will delete an item from the WordPress REST API.

func (*Client) Do

func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*Response, error)

Do sends an API request and returns the API response. The API response is JSON decoded and stored in the value pointed to by v, or returned as an error if an API error has occurred. If v implements the io.Writer interface, the raw response body will be written to v, without attempting to first decode it.

The provided ctx must be non-nil. If it is canceled or times out, ctx.Err() will be returned.

func (*Client) Get

func (c *Client) Get(ctx context.Context, url string, params interface{}, result interface{}) (*Response, error)

Get returns a single item from the WordPress REST API for the given parameters.

func (*Client) List

func (c *Client) List(ctx context.Context, url string, params interface{}, result interface{}) (*Response, error)

List is a generic function that will return a list of items from the WordPress REST API.

func (*Client) NewRequest

func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error)

NewRequest creates an API request. A relative URL can be provided in urlStr, in which case it is resolved relative to the baseURL of the Client. Relative URLs should always be specified without a preceding slash. If specified, the value pointed to by body is JSON encoded and included as the request body.

func (*Client) PostData

func (c *Client) PostData(ctx context.Context, urlStr string, content []byte, contentType string, filename string, result interface{}) (*Response, error)

PostData allows uploading of binary objects to the WordPress REST API.

func (*Client) Update

func (c *Client) Update(ctx context.Context, url string, content interface{}, result interface{}) (*Response, error)

Update will update an item on the WordPress REST API.

type Comment

type Comment struct {
	ID              int            `json:"id,omitempty"`
	AvatarURL       string         `json:"avatar_url,omitempty"`
	AvatarURLs      AvatarURLS     `json:"avatar_urls,omitempty"`
	Author          int            `json:"author,omitempty"`
	AuthorEmail     string         `json:"author_email,omitempty"`
	AuthorIP        string         `json:"author_ip,omitempty"`
	AuthorName      string         `json:"author_name,omitempty"`
	AuthorURL       string         `json:"author_url,omitempty"`
	AuthorUserAgent string         `json:"author_user_agent,omitempty"`
	Content         RenderedString `json:"content,omitempty"`
	Date            Time           `json:"date,omitempty"`
	DateGMT         Time           `json:"date_gmt,omitempty"`
	Karma           int            `json:"karma,omitempty"`
	Link            string         `json:"link,omitempty"`
	Parent          int            `json:"parent,omitempty"`
	Post            int            `json:"post,omitempty"`
	Status          string         `json:"status,omitempty"`
	Type            string         `json:"type,omitempty"`
}

Comment represents a WordPress post comment.

type CommentListOptions

type CommentListOptions struct {
	After         *time.Time `url:"after,omitempty"`                   // Limit response to comments published after a given ISO8601 compliant date.
	Author        []int      `url:"author,omitempty,brackets"`         // Limit result set to comments assigned to specific user IDs. Requires authorization.
	AuthorEmail   string     `url:"author_email,omitempty"`            // Limit result set to that from a specific author email. Requires authorization.
	AuthorExclude []int      `url:"author_exclude,omitempty,brackets"` // Ensure result set excludes comments assigned to specific user IDs. Requires authorization.
	Before        *time.Time `url:"before,omitempty"`                  // Limit response to comments published before a given ISO8601 compliant date.
	Parent        []int      `url:"parent,omitempty,brackets"`         // Limit result set to comments of specific parent IDs.
	ParentExclude []int      `url:"parent_exclude,omitempty,brackets"` // Ensure result set excludes specific parent IDs.
	Password      string     `url:"password,omitempty"`                // The password for the post if it is password protected.
	Post          []int      `url:"post,omitempty,brackets"`           // Limit result set to comments assigned to specific post IDs.
	Status        string     `url:"status,omitempty"`                  // Limit result set to comments assigned a specific status. Requires authorization.
	Type          string     `url:"type,omitempty"`                    // Limit result set to comments assigned a specific type. Requires authorization.

	ListOptions
}

CommentListOptions are options that can be passed to List().

type CommentsService

type CommentsService service

CommentsService provides access to the comment related functions in the WordPress REST API.

func (*CommentsService) Create

func (c *CommentsService) Create(ctx context.Context, newComment *Comment) (*Comment, *Response, error)

Create creates a new comment.

func (*CommentsService) Delete

func (c *CommentsService) Delete(ctx context.Context, id int, params interface{}) (*Comment, *Response, error)

Delete removes the comment with the given id.

func (*CommentsService) Get

func (c *CommentsService) Get(ctx context.Context, id int, params interface{}) (*Comment, *Response, error)

Get returns a single comment for the given id.

func (*CommentsService) List

List returns a list of comments.

func (*CommentsService) Update

func (c *CommentsService) Update(ctx context.Context, id int, post *Comment) (*Comment, *Response, error)

Update updates a single comment with the given id.

type DeleteResponse

type DeleteResponse struct {
	Deleted  bool            `json:"deleted"`
	Previous json.RawMessage `json:"previous"`
}

DeleteResponse is used when deleting an object.

type DiscoveredAPI

type DiscoveredAPI struct {
	BaseURL       string
	DiscoveredURL string
	ViaHeader     bool
	ViaHTML       bool
	Client        *Client
	BasicInfo     *RootInfo
}

DiscoveredAPI is a struct containing details about a discovered WordPress REST API.

func DiscoverAPI

func DiscoverAPI(baseURL string, getRootInfo bool) (*DiscoveredAPI, error)

DiscoverAPI will discover the API root URL for the given base URL.

type Error

type Error struct {
	Response *http.Response // HTTP response that caused this error
	Code     string         `json:"code"`
	Message  string         `json:"message"`
	Data     struct {
		Status int               `json:"status"`
		Params map[string]string `json:"params"`
	} `json:"data"`
}

Error is a generic WordPress error container.

func (*Error) Error

func (e *Error) Error() string

type ListOptions

type ListOptions struct {
	Context string `url:"context,omitempty"`          // Scope under which the request is made; determines fields present in response.
	Exclude []int  `url:"exclude,omitempty,brackets"` // Ensure result set excludes specific IDs.
	Include []int  `url:"include,omitempty,brackets"` // Limit result set to specific IDs.
	Offset  int    `url:"offset,omitempty"`           // Offset the result set by a specific number of items.
	Order   string `url:"order,omitempty"`            // Order sort attribute ascending or descending.
	OrderBy string `url:"orderby,omitempty"`          // Sort collection by object attribute.
	Page    int    `url:"page,omitempty"`             // Current page of the collection.
	PerPage int    `url:"per_page,omitempty"`         // Maximum number of items to be returned in result set.
	Search  string `url:"search,omitempty"`           // Limit results to those matching a string.
}

ListOptions specifies the optional parameters to various List methods that support pagination.

type Media

type Media struct {
	ID           int            `json:"id,omitempty"`
	Date         Time           `json:"date,omitempty"`
	DateGMT      Time           `json:"date_gmt,omitempty"`
	GUID         RenderedString `json:"guid,omitempty"`
	Link         string         `json:"link,omitempty"`
	Modified     Time           `json:"modified,omitempty"`
	ModifiedGMT  Time           `json:"modifiedGMT,omitempty"`
	Password     string         `json:"password,omitempty"`
	Slug         string         `json:"slug,omitempty"`
	Status       string         `json:"status,omitempty"`
	Type         string         `json:"type,omitempty"`
	Title        RenderedString `json:"title,omitempty"`
	Author       int            `json:"author,omitempty"`
	MediaStatus  string         `json:"media_status,omitempty"`
	PingStatus   string         `json:"ping_status,omitempty"`
	AltText      string         `json:"alt_text,omitempty"`
	Caption      RenderedString `json:"caption,omitempty"`
	Description  RenderedString `json:"description,omitempty"`
	MediaType    string         `json:"media_type,omitempty"`
	MediaDetails MediaDetails   `json:"media_details,omitempty"`
	Post         int            `json:"post,omitempty"`
	SourceURL    string         `json:"source_url,omitempty"`
}

Media represents a WordPress post media.

type MediaDetails

type MediaDetails struct {
	Raw       string                 `json:"raw,omitempty"`
	Rendered  string                 `json:"rendered,omitempty"`
	Width     int                    `json:"width,omitempty"`
	Height    int                    `json:"height,omitempty"`
	File      string                 `json:"file,omitempty"`
	Sizes     MediaDetailsSizes      `json:"sizes,omitempty"`
	ImageMeta map[string]interface{} `json:"image_meta,omitempty"`
}

MediaDetails describes specific details about media.

type MediaDetailsSizes

type MediaDetailsSizes struct {
	Thumbnail MediaDetailsSizesItem `json:"thumbnail,omitempty"`
	Medium    MediaDetailsSizesItem `json:"medium,omitempty"`
	Large     MediaDetailsSizesItem `json:"large,omitempty"`
	Full      MediaDetailsSizesItem `json:"full,omitempty"`
}

MediaDetailsSizes provides different sizes of the same media item.

type MediaDetailsSizesItem

type MediaDetailsSizesItem struct {
	File      string `json:"file,omitempty"`
	Width     int    `json:"width,omitempty"`
	Height    int    `json:"height,omitempty"`
	MimeType  string `json:"mime_type,omitempty"`
	SourceURL string `json:"source_url,omitempty"`
}

MediaDetailsSizesItem provides details for a single media item's size.

type MediaListOptions

type MediaListOptions struct {
	After         *time.Time `url:"after,omitempty"`                   // Limit response to posts published after a given ISO8601 compliant date.
	Author        []int      `url:"author,omitempty,brackets"`         // Limit result set to posts assigned to specific authors.
	AuthorExclude []int      `url:"author_exclude,omitempty,brackets"` // Ensure result set excludes posts assigned to specific authors.
	Before        *time.Time `url:"before,omitempty"`                  // Limit response to posts published before a given ISO8601 compliant date.
	MediaType     string     `url:"media_type,omitempty"`              // Limit result set to attachments of a particular media type.
	MimeType      string     `url:"mime_type,omitempty"`               // Limit result set to attachments of a particular MIME type.
	Parent        []int      `url:"parent,omitempty,brackets"`         // Limit result set to items with particular parent IDs.
	ParentExclude []int      `url:"parent_exclude,omitempty,brackets"` // Limit result set to all items except those of a particular parent ID.
	Slug          []string   `url:"slug,omitempty,brackets"`           // Limit result set to posts with one or more specific slugs.
	Status        []string   `url:"status,omitempty,brackets"`         // Limit result set to posts assigned one or more statuses.

	ListOptions
}

MediaListOptions are options that can be passed to List().

type MediaService

type MediaService service

MediaService provides access to the media related functions in the WordPress REST API.

func (*MediaService) Create

func (c *MediaService) Create(ctx context.Context, options *MediaUploadOptions) (*Media, *Response, error)

Create creates a new media.

func (*MediaService) Delete

func (c *MediaService) Delete(ctx context.Context, id int, params interface{}) (*Media, *Response, error)

Delete removes the media item with the given id.

func (*MediaService) Get

func (c *MediaService) Get(ctx context.Context, id int, params interface{}) (*Media, *Response, error)

Get returns a single media item for the given id.

func (*MediaService) List

func (c *MediaService) List(ctx context.Context, opts *MediaListOptions) ([]*Media, *Response, error)

List returns a list of medias.

type MediaUploadOptions

type MediaUploadOptions struct {
	Filename    string
	ContentType string
	Data        []byte
}

MediaUploadOptions are options that can be passed to Create().

type Page

type Page struct {
	ID            int            `json:"id,omitempty"`
	Date          Time           `json:"date,omitempty"`
	DateGMT       Time           `json:"date_gmt,omitempty"`
	GUID          RenderedString `json:"guid,omitempty"`
	Link          string         `json:"link,omitempty"`
	Modified      Time           `json:"modified,omitempty"`
	ModifiedGMT   Time           `json:"modifiedGMT,omitempty"`
	Password      string         `json:"password,omitempty"`
	Slug          string         `json:"slug,omitempty"`
	Status        string         `json:"status,omitempty"`
	Type          string         `json:"type,omitempty"`
	Parent        int            `json:"parent,omitempty"`
	Title         RenderedString `json:"title,omitempty"`
	Content       RenderedString `json:"content,omitempty"`
	Author        int            `json:"author,omitempty"`
	Excerpt       RenderedString `json:"excerpt,omitempty"`
	FeaturedImage int            `json:"featured_image,omitempty"`
	CommentStatus string         `json:"comment_status,omitempty"`
	PingStatus    string         `json:"ping_status,omitempty"`
	MenuOrder     int            `json:"menu_order,omitempty"`
	Template      string         `json:"template,omitempty"`
	// contains filtered or unexported fields
}

Page represents a WordPress page.

func (*Page) Populate

func (entity *Page) Populate(ctx context.Context, params interface{}) (*Page, *Response, error)

Populate will fill a manually initialized page with the collection information.

func (*Page) Revisions

func (entity *Page) Revisions() *RevisionsService

Revisions gets the revisions of a single page.

type PageListOptions

type PageListOptions struct {
	After         *time.Time `url:"after,omitempty"`                   // Limit response to posts published after a given ISO8601 compliant date.
	Author        []int      `url:"author,omitempty,brackets"`         // Limit result set to posts assigned to specific authors.
	AuthorExclude []int      `url:"author_exclude,omitempty,brackets"` // Ensure result set excludes posts assigned to specific authors.
	Before        *time.Time `url:"before,omitempty"`                  // Limit response to posts published before a given ISO8601 compliant date.
	MenuOrder     int        `url:"menu_order,omitempty"`              // Limit result set to posts with a specific menu_order value.
	Parent        []int      `url:"parent,omitempty,brackets"`         // Limit result set to items with particular parent IDs.
	ParentExclude []int      `url:"parent_exclude,omitempty,brackets"` // Limit result set to all items except those of a particular parent ID.
	Slug          []string   `url:"slug,omitempty,brackets"`           // Limit result set to posts with one or more specific slugs.
	Status        []string   `url:"status,omitempty,brackets"`         // Limit result set to posts assigned one or more statuses.

	ListOptions
}

PageListOptions are options that can be passed to List().

type PagesService

type PagesService service

PagesService provides access to the page related functions in the WordPress REST API.

func (*PagesService) Create

func (c *PagesService) Create(ctx context.Context, newPage *Page) (*Page, *Response, error)

Create creates a new page.

func (*PagesService) Delete

func (c *PagesService) Delete(ctx context.Context, id int, params interface{}) (*Page, *Response, error)

Delete removes the page with the given id.

func (*PagesService) Entity

func (c *PagesService) Entity(id int) *Page

Entity returns a basic page for the given id.

func (*PagesService) Get

func (c *PagesService) Get(ctx context.Context, id int, params interface{}) (*Page, *Response, error)

Get returns a single page for the given id.

func (*PagesService) List

func (c *PagesService) List(ctx context.Context, opts *PageListOptions) ([]*Page, *Response, error)

List returns a list of pages.

func (*PagesService) Update

func (c *PagesService) Update(ctx context.Context, id int, page *Page) (*Page, *Response, error)

Update updates a single page with the given id.

type Post

type Post struct {
	Author        int            `json:"author,omitempty"`
	Categories    []int          `json:"categories,omitempty"`
	CommentStatus string         `json:"comment_status,omitempty"`
	Content       RenderedString `json:"content,omitempty"`
	Date          Time           `json:"date,omitempty"`
	DateGMT       Time           `json:"date_gmt,omitempty"`
	Excerpt       RenderedString `json:"excerpt,omitempty"`
	FeaturedMedia int            `json:"featured_media,omitempty"`
	Format        string         `json:"format,omitempty"`
	GUID          RenderedString `json:"guid,omitempty"`
	ID            int            `json:"id,omitempty"`
	Link          string         `json:"link,omitempty"`
	Modified      Time           `json:"modified,omitempty"`
	ModifiedGMT   Time           `json:"modified_gmt,omitempty"`
	Password      string         `json:"password,omitempty"`
	PingStatus    string         `json:"ping_status,omitempty"`
	Slug          string         `json:"slug,omitempty"`
	Status        string         `json:"status,omitempty"`
	Sticky        bool           `json:"sticky,omitempty"`
	Subtitle      string         `json:"wps_subtitle,omitempty"`
	Tags          []int          `json:"tags,omitempty"`
	Template      string         `json:"template,omitempty"`
	Title         RenderedString `json:"title,omitempty"`
	Type          string         `json:"type,omitempty"`
	// contains filtered or unexported fields
}

Post represents a WordPress post.

func (*Post) Populate

func (entity *Post) Populate(ctx context.Context, params interface{}) (*Post, *Response, error)

Populate will fill a manually initialized post with the collection information.

func (*Post) Revisions

func (entity *Post) Revisions() *RevisionsService

Revisions gets the revisions of a single post.

func (*Post) Terms

func (entity *Post) Terms() *PostsTermsService

Terms gets the terms of a single post.

type PostListOptions

type PostListOptions struct {
	After             *time.Time `url:"after,omitempty"`                       // Limit response to posts published after a given ISO8601 compliant date.
	Author            []int      `url:"author,omitempty,brackets"`             // Limit result set to posts assigned to specific authors.
	AuthorExclude     []int      `url:"author_exclude,omitempty,brackets"`     // Ensure result set excludes posts assigned to specific authors.
	Before            *time.Time `url:"before,omitempty"`                      // Limit response to posts published before a given ISO8601 compliant date.
	Categories        []int      `url:"categories,omitempty,brackets"`         // Limit result set to all items that have the specified term assigned in the categories taxonomy.
	CategoriesExclude []int      `url:"categories_exclude,omitempty,brackets"` // Limit result set to all items except those that have the specified term assigned in the categories taxonomy.
	Slug              []string   `url:"slug,omitempty,brackets"`               // Limit result set to posts with one or more specific slugs.
	Status            []string   `url:"status,omitempty,brackets"`             // Limit result set to posts assigned one or more statuses.
	Sticky            bool       `url:"sticky,omitempty"`                      // Limit result set to items that are sticky.
	Tags              []int      `url:"tags,omitempty,brackets"`               // Limit result set to all items that have the specified term assigned in the tags taxonomy.
	TagsExclude       []int      `url:"tags_exclude,omitempty,brackets"`       // Limit result set to all items except those that have the specified term assigned in the tags taxonomy.

	ListOptions
}

PostListOptions are options that can be passed to List().

type PostsService

type PostsService service

PostsService provides access to the post related functions in the WordPress REST API.

func (*PostsService) Create

func (c *PostsService) Create(ctx context.Context, newPost *Post) (*Post, *Response, error)

Create creates a new post.

func (*PostsService) Delete

func (c *PostsService) Delete(ctx context.Context, id int, params interface{}) (*Post, *Response, error)

Delete removes the post with the given id.

func (*PostsService) Entity

func (c *PostsService) Entity(id int) *Post

Entity returns a basic post for the given id.

func (*PostsService) Get

func (c *PostsService) Get(ctx context.Context, id int, params interface{}) (*Post, *Response, error)

Get returns a single post for the given id.

func (*PostsService) List

func (c *PostsService) List(ctx context.Context, opts *PostListOptions) ([]*Post, *Response, error)

List returns a list of posts.

func (*PostsService) Update

func (c *PostsService) Update(ctx context.Context, id int, post *Post) (*Post, *Response, error)

Update updates a single post with the given id.

type PostsTerm

type PostsTerm struct {
	ID          int    `json:"id,omitempty"`
	Count       int    `json:"integer,omitempty"`
	Description string `json:"description,omitempty"`
	Link        string `json:"link,omitempty"`
	Name        string `json:"name"`
	Slug        string `json:"slug,omitempty"`
	Taxonomy    string `json:"taxonomy,omitempty"`
	Parent      int    `json:"parent,omitempty"`
}

PostsTerm represents a WordPress post post term.

type PostsTermsService

type PostsTermsService struct {
	// contains filtered or unexported fields
}

PostsTermsService provides access to the post term related functions in the WordPress REST API.

func (*PostsTermsService) Category

Category returns the categories of a post.

func (*PostsTermsService) List

func (c *PostsTermsService) List(ctx context.Context, taxonomy string, params interface{}) ([]*PostsTerm, *Response, error)

List returns a list of post terms.

func (*PostsTermsService) Tag

Tag returns the tags of a post.

type PostsTermsTaxonomyService

type PostsTermsTaxonomyService struct {
	// contains filtered or unexported fields
}

PostsTermsTaxonomyService contains data about the post terms taxonomy service

func (*PostsTermsTaxonomyService) Create

Create creates a new post term.

func (*PostsTermsTaxonomyService) Delete

func (c *PostsTermsTaxonomyService) Delete(ctx context.Context, id int, params interface{}) (*PostsTerm, *Response, error)

Delete removes the post term with the given id.

func (*PostsTermsTaxonomyService) Get

func (c *PostsTermsTaxonomyService) Get(ctx context.Context, id int, params interface{}) (*PostsTerm, *Response, error)

Get returns a single post term for the given id.

func (*PostsTermsTaxonomyService) List

func (c *PostsTermsTaxonomyService) List(ctx context.Context, params interface{}) ([]*PostsTerm, *Response, error)

List returns a list of post terms.

type RenderedString

type RenderedString struct {
	Raw      string `json:"raw,omitempty"`
	Rendered string `json:"rendered,omitempty"`
}

RenderedString contains a raw and rendered version of a string such as title, content, excerpt, etc.

type Response

type Response struct {
	*http.Response

	TotalRecords int
	TotalPages   int
	PreviousPage int
	NextPage     int
}

Response is a WordPress REST API response. This wraps the standard http.Response returned from WordPress and provides convenient access to things like pagination data.

type Revision

type Revision struct {
	ID          int            `json:"id,omitempty"`
	Author      int            `json:"author,omitempty"`
	Date        Time           `json:"date,omitempty"`
	DateGMT     Time           `json:"date_gmt,omitempty"`
	GUID        RenderedString `json:"guid,omitempty"`
	Modified    Time           `json:"modified,omitempty"`
	ModifiedGMT Time           `json:"modified_gmt,omitempty"`
	Parent      int            `json:"parent,omitempty"`
	Slug        string         `json:"slug,omitempty"`
	Title       RenderedString `json:"title,omitempty"`
	Content     RenderedString `json:"content,omitempty"`
	Excerpt     RenderedString `json:"excerpt,omitempty"`
}

Revision represents a WordPress page/post revision.

type RevisionsService

type RevisionsService struct {
	// contains filtered or unexported fields
}

RevisionsService provides access to the revision related functions in the WordPress REST API.

func (*RevisionsService) Delete

func (c *RevisionsService) Delete(ctx context.Context, id int, params interface{}) (*Revision, *Response, error)

Delete removes the revision with the given id.

func (*RevisionsService) Get

func (c *RevisionsService) Get(ctx context.Context, id int, params interface{}) (*Revision, *Response, error)

Get returns a single revision for the given id.

func (*RevisionsService) List

func (c *RevisionsService) List(ctx context.Context, params interface{}) ([]*Revision, *Response, error)

List returns a list of revisions.

type RootInfo

type RootInfo struct {
	Authentication     interface{} `json:"authentication"`
	Description        string      `json:"description"`
	GMTOffset          int         `json:"gmt_offset"`
	HomeURL            string      `json:"home"`
	Name               string      `json:"name"`
	Namespaces         []string    `json:"namespaces"`
	PermalinkStructure string      `json:"permalink_structure"`
	TimezoneString     string      `json:"timezone_string"`
	URL                string      `json:"url"`

	Location *time.Location `json:"-"`
}

RootInfo is a struct containing basic and publicly available information about the WordPress REST API.

type Settings

type Settings struct {
	Title                string `json:"title"`
	Description          string `json:"description"`
	URL                  string `json:"url"`
	Email                string `json:"email"`
	Timezone             string `json:"timezone"`
	DateFormat           string `json:"date_format"`
	TimeFormat           string `json:"time_format"`
	StartOfWeek          int    `json:"start_of_week"`
	Language             string `json:"language"`
	UseSmilies           bool   `json:"use_smilies"`
	DefaultCategory      int    `json:"default_category"`
	DefaultPostFormat    string `json:"default_post_format"`
	PostsPerPage         int    `json:"posts_per_page"`
	DefaultPingStatus    string `json:"default_ping_status"`
	DefaultCommentStatus string `json:"default_comment_status"`
}

Settings represents a WordPress settings.

type SettingsService

type SettingsService service

SettingsService provides access to the settings related functions in the WordPress REST API.

func (*SettingsService) List

List returns a list of settingss.

type Status

type Status struct {
	Name       string `json:"name,omitempty"`
	Private    bool   `json:"private,omitempty"`
	Public     bool   `json:"public,omitempty"`
	Queryable  bool   `json:"queryable,omitempty"`
	ShowInList bool   `json:"show_in_list,omitempty"`
	Slug       string `json:"slug,omitempty"`
}

Status represents a WordPress post status.

type Statuses

type Statuses struct {
	Publish Status `json:"publish,omitempty"`
	Future  Status `json:"future,omitempty"`
	Draft   Status `json:"draft,omitempty"`
	Pending Status `json:"pending,omitempty"`
	Private Status `json:"private,omitempty"`
}

Statuses describes multiple Statuses.

type StatusesService

type StatusesService service

StatusesService provides access to the Status related functions in the WordPress REST API.

func (*StatusesService) Get

func (c *StatusesService) Get(ctx context.Context, slug string, params interface{}) (*Status, *Response, error)

Get returns a single status for the given id.

func (*StatusesService) List

func (c *StatusesService) List(ctx context.Context, params interface{}) (*Statuses, *Response, error)

List returns a list of statuses.

type Tag

type Tag struct {
	ID          int    `json:"id,omitempty"`
	Count       int    `json:"count,omitempty"`
	Description string `json:"description,omitempty"`
	Link        string `json:"link,omitempty"`
	Name        string `json:"name,omitempty"`
	Slug        string `json:"slug,omitempty"`
	Taxonomy    string `json:"taxonomy,omitempty"`
}

Tag represents a WordPress page/post tag.

type TagListOptions

type TagListOptions struct {
	HideEmpty bool     `url:"hide_empty,omitempty"`    // Whether to hide terms not assigned to any posts.
	Post      int      `url:"post,omitempty"`          // Limit result set to terms assigned to a specific post.
	Slug      []string `url:"slug,omitempty,brackets"` // Limit result set to terms with one or more specific slugs.

	ListOptions
}

TagListOptions are options that can be passed to List().

type TagsService

type TagsService service

TagsService provides access to the Tag related functions in the WordPress REST API.

func (*TagsService) Create

func (c *TagsService) Create(ctx context.Context, newTag *Tag) (*Tag, *Response, error)

Create creates a new tag.

func (*TagsService) Delete

func (c *TagsService) Delete(ctx context.Context, id int, params interface{}) (*Tag, *Response, error)

Delete removes the tag with the given id.

func (*TagsService) Get

func (c *TagsService) Get(ctx context.Context, id int, params interface{}) (*Tag, *Response, error)

Get returns a single tag for the given id.

func (*TagsService) List

func (c *TagsService) List(ctx context.Context, opts *TagListOptions) ([]*Tag, *Response, error)

List returns a list of tags.

func (*TagsService) Update

func (c *TagsService) Update(ctx context.Context, id int, post *Tag) (*Tag, *Response, error)

Update updates a single tag with the given id.

type TaxonomiesService

type TaxonomiesService service

TaxonomiesService provides access to the Taxonomies related functions in the WordPress REST API.

func (*TaxonomiesService) Get

func (c *TaxonomiesService) Get(ctx context.Context, slug string, params interface{}) (*Taxonomy, *Response, error)

Get returns a single taxonomy for the given id.

func (*TaxonomiesService) List

func (c *TaxonomiesService) List(ctx context.Context, params interface{}) (map[string]Taxonomy, *Response, error)

List returns a list of taxonomies.

type Taxonomy

type Taxonomy struct {
	Description  string                 `json:"description,omitempty"`
	Hierarchical bool                   `json:"hierarchical,omitempty"`
	Labels       map[string]interface{} `json:"labels,omitempty"`
	Name         string                 `json:"name,omitempty"`
	ShowCloud    bool                   `json:"show_cloud,omitempty"`
	Slug         string                 `json:"slug,omitempty"`
	Types        []string               `json:"types,omitempty"`
}

Taxonomy represents a WordPress taxonomy.

type Term

type Term struct {
	ID          int    `json:"id,omitempty"`
	Count       int    `json:"integer,omitempty"`
	Description string `json:"description,omitempty"`
	Link        string `json:"link,omitempty"`
	Name        string `json:"name"`
	Slug        string `json:"slug,omitempty"`
	Taxonomy    string `json:"taxonomy,omitempty"`
	Parent      int    `json:"parent,omitempty"`
}

Term represents a WordPress page/post term.

type TermsService

type TermsService service

TermsService provides access to the Terms related functions in the WordPress REST API.

func (*TermsService) Category

func (c *TermsService) Category() *TermsTaxonomyService

Category returns the terms taxonomy service configured for categories.

func (*TermsService) List

func (c *TermsService) List(ctx context.Context, taxonomy string, params interface{}) ([]*Term, *Response, error)

List returns a list of terms.

func (*TermsService) Tag

Tag returns the terms taxonomy service configured for tags.

type TermsTaxonomyService

type TermsTaxonomyService struct {
	// contains filtered or unexported fields
}

TermsTaxonomyService contains information about a taxonomy term.

func (*TermsTaxonomyService) Create

func (c *TermsTaxonomyService) Create(ctx context.Context, newTerm *Term) (*Term, *Response, error)

Create creates a new term.

func (*TermsTaxonomyService) Delete

func (c *TermsTaxonomyService) Delete(ctx context.Context, id int, params interface{}) (*Term, *Response, error)

Delete removes the term with the given id.

func (*TermsTaxonomyService) Get

func (c *TermsTaxonomyService) Get(ctx context.Context, id int, params interface{}) (*Term, *Response, error)

Get returns a single term for the given id.

func (*TermsTaxonomyService) List

func (c *TermsTaxonomyService) List(ctx context.Context, params interface{}) ([]*Term, *Response, error)

List returns a list of terms.

func (*TermsTaxonomyService) Update

func (c *TermsTaxonomyService) Update(ctx context.Context, id int, post *Term) (*Term, *Response, error)

Update updates a single term with the given id.

type Time

type Time struct {
	time.Time
}

Time is a wrapper around time.Time with custom JSON marshal/unmarshal functions for the WordPress specific timestamp formats.

func (*Time) MarshalJSON

func (t *Time) MarshalJSON() ([]byte, error)

MarshalJSON returns a WordPress formatted timestamp.

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals the timestamp with one of the WordPress specific formats.

type Type

type Type struct {
	Description  string     `json:"description,omitempty"`
	Hierarchical bool       `json:"hierarchical,omitempty"`
	Name         string     `json:"name,omitempty"`
	Slug         string     `json:"slug,omitempty"`
	Labels       TypeLabels `json:"labels,omitempty"`
}

Type represents a WordPress item type.

type TypeLabels

type TypeLabels struct {
	Name            string `json:"name,omitempty"`
	SingularName    string `json:"singular_name,omitempty"`
	AddNew          string `json:"add_new,omitempty"`
	AddNewItem      string `json:"add_new_item,omitempty"`
	EditItem        string `json:"edit_item,omitempty"`
	NewItem         string `json:"new_item,omitempty"`
	ViewItem        string `json:"view_item,omitempty"`
	SearchItems     string `json:"search_items,omitempty"`
	NotFound        string `json:"not_found,omitempty"`
	NotFoundInTrash string `json:"not_found_in_trash,omitempty"`
	ParentItemColon string `json:"parent_item_colon,omitempty"`
	AllItems        string `json:"all_items,omitempty"`
	MenuName        string `json:"menu_name,omitempty"`
	NameAdminBar    string `json:"name_admin_bar,omitempty"`
}

TypeLabels represents a label that applies to a WordPress Type.

type Types

type Types map[string]Type

Types represents the assigned types for each item type.

type TypesService

type TypesService service

TypesService provides access to the Type related functions in the WordPress REST API.

func (*TypesService) Get

func (c *TypesService) Get(ctx context.Context, slug string, params interface{}) (*Type, *Response, error)

Get returns a single type for the given id.

func (*TypesService) List

func (c *TypesService) List(ctx context.Context, params interface{}) (*Types, *Response, error)

List returns a list of types.

type User

type User struct {
	ID                int                    `json:"id,omitempty"`
	AvatarURL         string                 `json:"avatar_url,omitempty"`
	AvatarURLs        AvatarURLS             `json:"avatar_urls,omitempty"`
	Capabilities      map[string]interface{} `json:"capabilities,omitempty"`
	Description       string                 `json:"description,omitempty"`
	Email             string                 `json:"email,omitempty"`
	ExtraCapabilities map[string]interface{} `json:"extra_capabilities,omitempty"`
	FirstName         string                 `json:"first_name,omitempty"`
	LastName          string                 `json:"last_name,omitempty"`
	Link              string                 `json:"link,omitempty"`
	Name              string                 `json:"name,omitempty"`
	Nickname          string                 `json:"nickname,omitempty"`
	RegisteredDate    Time                   `json:"registered_date,omitempty"`
	Roles             []string               `json:"roles,omitempty"`
	Slug              string                 `json:"slug,omitempty"`
	URL               string                 `json:"url,omitempty"`
	Username          string                 `json:"username,omitempty"`
	Password          string                 `json:"password,omitempty"`
	Locale            string                 `json:"locale,omitempty"`
}

User represents a WordPress user.

type UserListOptions

type UserListOptions struct {
	Roles []string `url:"roles,omitempty,brackets"` // Limit result set to users matching at least one specific role provided. Accepts csv list or single role.
	Slug  []string `url:"slug,omitempty,brackets"`  // Limit result set to users with one or more specific slugs.

	ListOptions
}

UserListOptions are options that can be passed to List().

type UsersService

type UsersService service

UsersService provides access to the Users related functions in the WordPress REST API.

func (*UsersService) Create

func (c *UsersService) Create(ctx context.Context, newUser *User) (*User, *Response, error)

Create creates a new user.

func (*UsersService) Delete

func (c *UsersService) Delete(ctx context.Context, id int, params interface{}) (*User, *Response, error)

Delete removes the user with the given id.

func (*UsersService) Get

func (c *UsersService) Get(ctx context.Context, id int, params interface{}) (*User, *Response, error)

Get returns a single user for the given id.

func (*UsersService) List

func (c *UsersService) List(ctx context.Context, opts *UserListOptions) ([]*User, *Response, error)

List returns a list of users.

func (*UsersService) Me

func (c *UsersService) Me(ctx context.Context, params interface{}) (*User, *Response, error)

Me returns information about the currently authenticated user.

func (*UsersService) Update

func (c *UsersService) Update(ctx context.Context, id int, user *User) (*User, *Response, error)

Update updates a single user with the given id.

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL